用來陳述 code 跟特定訊息的關聯,很像 Java 中的 Annotation。
[ApiController] // Attribute for class [Route("api/[controller]")] // Attribute for class with parameter public class BookController : ControllerBase { [HttpGet] // Attribute for method public ActionResult Get() { // ... } [HttpGet("{bookId}")] // Attribute for method with parameter public ActionResult Get(int bookId) { // ... } }
客製一個最簡單的 Attribute (沒有帶任何參數),
只需要建立一個 Attribute Class 、繼承 Attribute ,便可使用:
public class Not4InsertAttribute : Attribute { } public class Book { [Not4Insert] // Or [Not4InsertAttribute] public int Id { get; set; } }
public class Not4InsertAttribute : Attribute { // named parameter public int? OnlyWhenLessThan { get; set; } } public class GreaterThanAttribute : Attribute { // named parameter public bool AllowEqual { get; set; } = false; private int GreaterThan { set; } public GreaterThanAttribute (int greaterThan) // positional parameter { GreaterThan = greaterThan; } } public class Book { // Attribute without parameter [Not4Insert] public int Id { get; set; } // Attribute with named parameter [Not4Insert(OnlyWhenLessThan = 1)] // Attribute with positional parameter [GreaterThan(0)] public int AuthorId { get; set; } // Attribute with positional parameter & named parameter [GreaterThan(1, AllowEqual = true)] public int PublisherId { get; set; } }
Attribute 的參數必須為下列類型:
bool
、byte
、char
、double
、float
、int
、long
、sbyte
、short
、string
、uint
、ulong
、ushort
、object
、System.Type
之一enum
(在建立 Attribute 時, IDE 可能不會提示建立了不符合類型限制的參數,但會造成編譯錯誤 。)
[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = true, Inherited = false)] public class Not4InsertAttribute : Attribute {}
// AllowMultiple為false時會編譯錯誤 [ExampleAttribute] [ExampleAttribute(10)] public class ForExample { }
[InheritedExampleAttribute] public class ForExample { [InheritedExampleAttribute] public virtual void MakeExample() {} } // Inherited 為 true 時, // Implementation 也會套用 InheritedExampleAttribute public class Implementation : ForExample { // Inherited 為 true 時, // override 的 MakeExample 也會套用 InheritedExampleAttribute public override void MakeExample() {} }
// 如果沒有找到會回傳 null Attribute? GetCustomAttribute (Target element, Type attributeType, bool inherit = false)
public class Not4InsertAttribute : Attribute { public int? OnlyWhenLessThan { get; set; } } public class Book { [Not4Insert] public int Id { get; set; } } public static void Main(string[] args) { // ... foreach(var propInfo in typeof(Book).GetProperties()) { // 記得轉型,才拿得到 Property var attribute = (Not4InsertAttribute) Attribute .GetCustomAttribute(propInfo, typeof(Not4InsertAttribute)); var onlyWhenLessThan = attribute.OnlyWhenLessThan; } // ... }