一、特性的本質就是:對屬性、方法、類加特性,本質就是new 一個特性類對象賦值給屬性、方法、類。
可以通過反射的方式取得特性的值,代碼如下:
①自定義特性
public class MyAttribute:Attribute{public string Name { get; set; }}
②實體類中使用自定義特性
public class AttributeTest{[MyAttribute(Name = "姓名")]public string Name { get; set; }}
③使用反射顯示自定義特性
Type t = typeof(AttributeTest【使用特性的類】); foreach (PropertyInfo propInfo in t.GetProperties()) {//這個.GetCustomAttribute是取得具體的特性,當然也有獲取全部特性的方法.GetCustomAttributesAttribute propAttribute = propInfo.GetCustomAttribute(typeof(MyAttribute【自定義特性類】), true);string strName = ((MyAttribute)propAttribute).Name;//結果就是“姓名”顯示出來 }
反射基礎知識
http://www.cnblogs.com/WarBlog/p/7346604.html
?