閱讀目錄
一:C#自定義Attribute
二:AttributeUsageAttribute中的3個屬性(Property)中的AttributeTargets
三:AttributeUsageAttribute中的3個屬性(Property)中的,AllowMultiple
四:AttributeUsageAttribute中的3個屬性(Property)中的Inherited
一:C#自定義Attribute
寫一個類繼承自System.Attribute就可以了
二:AttributeUsageAttribute中的3個屬性(Property)中的AttributeTargets
這個屬性類能應用於哪種類型上面,如下圖,我的例子中聲明屬性類HelperAttribute只能用於interface接口上面,而我實際應用於class上面編譯就報錯了說聲明類型不對
三:AttributeUsageAttribute中的3個屬性(Property)中的,AllowMultiple
能否多次聲明指定的屬性,如下圖AllowMultiple=false的話,我在一個類上聲明2次,編輯就報錯了
四:AttributeUsageAttribute中的3個屬性(Property)中的Inherited
我們在父類上聲明屬性類,而在子類上不聲明屬性類,把屬性類設置為Inherited = false,我們看到查找SubMyClass1類型沒有找到它的父類MyClass1的HelperAttribute屬性類,所以沒有任何輸出
我們改為Inherited = true后,再調試看到查找SubMyClass1類型找到了它父類的HelperAttribute屬性類,然后輸出描述
我們在父類上聲明屬性類,也在子類上聲明屬性類,把屬性類設置為 AllowMultiple = false, Inherited = true,我們看到查找SubMyClass1類型找到了它自己的HelperAttribute屬性類,然后輸出描述,沒有找到父類MyClass1的HelperAttribute屬性類,是因為 AllowMultiple = false不允許多重屬性,所以父類的HelperAttribute屬性類被子類SubMyClass1的HelperAttribute屬性類覆蓋了,所以最終只能找到子類的屬性類
我們再改為AllowMultiple = true, Inherited = true,我們看到查找SubMyClass1類型不但是找到了它自己的HelperAttribute屬性類而且找到了父類MyClass1的HelperAttribute屬性類,所以最終會輸出兩條信息
實例代碼
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Reflection; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace CustomizeAttribute 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 foreach (Attribute attr in typeof(SubMyClass1).GetCustomAttributes(true)) 15 { 16 HelperAttribute helperAtt = attr as HelperAttribute; 17 if (helperAtt != null) 18 { 19 Console.WriteLine("Name:{0} Description:{1}",helperAtt.Name, helperAtt.Description); 20 } 21 } 22 23 Console.ReadLine(); 24 } 25 } 26 27 [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 28 public class HelperAttribute : System.Attribute 29 { 30 private string _name; 31 private string _description; 32 33 public HelperAttribute(string des) 34 { 35 this._name = "Default name"; 36 this._description = des; 37 } 38 39 public HelperAttribute(string des1,string des2) 40 { 41 this._description = des1; 42 this._description = des2; 43 } 44 45 public string Description 46 { 47 get 48 { 49 return this._description; 50 } 51 set 52 { 53 this._description = value; 54 } 55 } 56 57 public string Name 58 { 59 get 60 { 61 return this._name; 62 } 63 set 64 { 65 this._name = value; 66 } 67 } 68 69 public string PrintMessage() 70 { 71 return "PrintMessage"; 72 } 73 } 74 75 [HelperAttribute("this is my class1")] 76 public class MyClass1 77 { 78 79 } 80 81 public class SubMyClass1 : MyClass1 82 { 83 84 } 85 86 87 [HelperAttribute("this is my class2", Name = "myclass2")] 88 public class MyClass2 89 { 90 91 } 92 93 [HelperAttribute("this is my class3", Name = "myclass3", Description = "New Description")] 94 public class MyClass3 95 { 96 97 } 98 99 [HelperAttribute("this is my class4", "this is my class4")] 100 public class MyClass4 101 { 102 103 } 104 }