所谓 “定制Attribute”,就是一个类的实例,它被序列化成驻留在元数据的一个字节流。
我们可以使用 Attribute 来保存注释:

1 namespace AttributeDemo 2 { 3 [AttributeUsage(AttributeTargets.Method,Inherited=false,AllowMultiple=true)] 4 public class HistoryAttribute:Attribute 5 { 6 public HistoryAttribute() 7 { 8 9 } 10 public HistoryAttribute(string Author, string UpdateDate, string Description) 11 { 12 this.Author = Author; 13 this.UpdateDate = UpdateDate; 14 this.Description = Description; 15 } 16 17 public string Author { get; set; } 18 public string UpdateDate { get; set; } 19 public string Description { get; set; } 20 21 } 22 }
在指定的方法上应用特性:

1 public class TestClass 2 { 3 [History("B_Z", "2013-12-30", "新建")] 4 [History("B_Z","2013-12-31","修改")] 5 6 public void Test() 7 { 8 9 } 10 }
然后,我们就可以利用反射来获取注释的内容:

1 public static void AttributeTestI() 2 { 3 4 //利用反射获取类型的方法 5 MemberInfo[] members = typeof(TestClass).FindMembers(MemberTypes.Method | MemberTypes.Constructor, 6 BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | 7 BindingFlags.DeclaredOnly, Type.FilterName, "*"); 8 foreach (var m in members) 9 { 10 Attribute[] attributes = Attribute.GetCustomAttributes(m); 11 foreach (var A in attributes) 12 { 13 HistoryAttribute history = A as HistoryAttribute; 14 if (history != null) 15 { 16 Console.WriteLine("Author:{0},UpdateDate:{1},Description:{2}", history.Author, history.UpdateDate, history.Description); 17 } 18 } 19 } 20 Console.Read(); 21 }
我也可以通过 “ISDefined” 来判断对象是否应用了指定的特性:

1 public static void AttributeTestII() 2 { 3 //判断该类型是否应用了HistoryAttribute特性 4 if (typeof(TestClass).IsDefined(typeof(HistoryAttribute), false)) 5 { 6 //如果是执行代码 7 Console.WriteLine("如果是执行代码A"); 8 } 9 else 10 { 11 //如果不是则执行其他代码 12 Console.WriteLine("如果不是执行代码B"); 13 } 14 Console.Read(); 15 }
以上就是个人对于定制 Attribute 的简单理解。
欢迎指教。