پشتیبانی از Generic Attributes در C# 11
نویسنده: وحید نصیری
تاریخ: ۱۴۰۱/۰۸/۲۵ ۱۱:۲۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class Student
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
}
public class WeatherForecast
{
[Required]
public int TemperatureC { get; set; }
[MinLength(50)]
public string Summary { get; set; }
} [AttributeUsage(AttributeTargets.Class)]
public class CustomDoNothingAttribute: Attribute
{
// Note the type parameter in the constructor
public CustomDoNothingAttribute(Type t)
{
ParamType = t;
}
public Type ParamType { get; }
} [CustomDoNothing(typeof(string))]
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
} [AttributeUsage(AttributeTargets.Class)]
public class CustomDoNothingAttribute<T> : Attribute
where T : class
{
public T ParamType { get; }
}
[CustomDoNothing<string>]
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
} [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class DecorateAttribute<T> : Attribute where T : class
{
// ....
} [Decorate<LoggerDecorator>]
[Decorate<TimerDecorator>]
public class SimpleWorker
{
// ....
} public class GenericAttribute<T> : Attribute { }
public class GenericType<T>
{
[GenericAttribute<T>] // Not allowed! generic attributes must be fully constructed types.
public string Method1() => default;
[GenericAttribute<string>]
public string Method2() => default;
} /// <summary>
/// Instantiates a new <see cref="ServiceFilterAttribute"/> instance.
/// </summary>
/// <param name="type">The <see cref="Type"/> of filter to find.</param>
public ServiceFilterAttribute(Type type)
{
ServiceType = type ?? throw new ArgumentNullException(nameof(type));
} public class TypeSafeServiceFilterAttribute<T> : ServiceFilterAttribute where T: IActionFilter
{
public TypeSafeServiceFilterAttribute():base(typeof(T))
{
}
} [Route("api/[controller]")]
[ApiController]
public class CoursesController : ControllerBase
{
[HttpGet]
[TypeSafeServiceFilterAttribute<ExampleFilter>()]
public IActionResult Get()
{
return Ok();
}
} ProducesResponseType<T> Produces<T> MiddlewareFilter<T> ModelBinder<T> ModelMetadataType<T> ServiceFilter<T> TypeFilter<T>