標籤:style blog color 使用 strong io 資料 cti
特性是一種有別於普通命令式編程的編程方式,通常被稱為申明式編程方式
所謂申明式的編程方式,就是指程式員只需申明某個模組會具有怎樣的特性,而無須關心如何去實現
1 [PermissionSetAttribute(SecurityAction.Demand,namespace="FullTrust")]2 class UseReflection 3 {4 //some code5 }
當一個特性被添加到某個元素上時,該元素就被認為具有了這個特性所代表的功能或性質
例如上述代碼UseReflection 類型在添加了PermissionSetAttribute之後,就會被認為需要有完全信任通行證才能運行
1 /// <summary> 2 /// 使用自訂特性 3 /// </summary> 4 [MyAttribute("UseMyAttribute")] 5 class UseMyAttribute 6 { 7 public static void TestMyAttribute() 8 { 9 Type t = typeof(UseMyAttribute);10 //得到自訂特性11 Object[] attribute = t.GetCustomAttributes(false);12 MyAttribute att = (MyAttribute)attribute[0];13 Console.WriteLine(att.ClassName);14 }15 }16 17 18 /// <summary>19 /// 自訂的特性20 /// </summary>21 [AttributeUsage(AttributeTargets.Class)]22 public class MyAttribute : Attribute 23 {24 private String _classname;25 public MyAttribute(string s) 26 {27 _classname = s;28 }29 public string ClassName 30 {31 get 32 {33 return _classname;34 }35 }36 }
特性可以應用在程式集,模組,類,結構,枚舉,構造方法,方法,屬性,欄位,事件,介面,參數,委託,返回參數和泛型參數這些目標元素之上,通過AttributeUsage特性可以限制自訂特性的使用範圍
.net提供的尋找是否申明指定特性的方法
- System.Attribute.IsDefined
這是一個高效判斷某個元素是否申明了某特性的方法,它的高效在於該方法不會實際地初始化特性
而只是尋找該中繼資料並且返回一個布爾型變數來指明是否尋找到指定的屬性
2. System.Attribute.GetCustomerAttribute
該方法用於得到申明在指定元素上的一個指定特性的執行個體對象,如果指定元素沒有包含指定的特性或其派生特性,則會返回NULL
同時如果指定元素申明了多次制定的特性或者其派生特性,則會拋出一個System.Reflection.AmbiguousMatchException的異常
3. System.Attribute.GetCustomerAttributes
該方法類似於System.Attribute.GetCustomerAttribute方法 不同的是該方法將以一數組的形式返回尋找到底合格所有特性對象
4. System.Reflection.CustomAttributeData
該類型擁有一個已重載的靜態方法GetCustomAttribte用已獲得一個IList<AttributeData>的對象,而每一個CustomAttributeData對象都封裝了特性的詳細 資訊
當一個特性申明了AttributeUsage特性並且顯式地將AllowMultiple屬性設定為true時,該特性就可以在同一元素上多次申明,否則地話編譯器將報錯