首先定義一個自定義的屬性類MyAttribute,該類需要繼承Attribute
public class MyAttribute : Attribute { /// <summary> /// 代碼 /// </summary> public string Code { get; set; } /// <summary> /// 描述 /// </summary> public string Msg { get; set; } public MyAttribute() { } public MyAttribute(string code,string msg) { this.Code = code; this.Msg = msg; } }
接下來定義一個使用MyAttribute的類AttributeTest
[MyAttribute("C01","類屬性描述")] public class AttributeTest { [My("C02","屬性描述")] // 等價於 [MyAttribute("C02","屬性描述")] public string Field { get; set; } [My("C03", "方法描述")] public void Method() { } }
測試讀取AttributeTest的MyAttribute特性信息,代碼如下:
static void Main(string[] args) { // 獲取類的屬性描述 var classIfno = typeof(AttributeTest).GetCustomAttribute<MyAttribute>(); // 獲取指定屬性的屬性描述 var fieldIfno = typeof(AttributeTest).GetProperty("Field").GetCustomAttribute<MyAttribute>(); // 獲取指定方法的屬性描述 var methodIfno = typeof(AttributeTest).GetMethod("Method").GetCustomAttribute<MyAttribute>(); Console.WriteLine(classIfno.Msg + " " + fieldIfno.Msg + " " + methodIfno.Msg); Console.ReadLine(); }
運行結果: