特性(Attribute)是用於在運行時傳遞程序中各類元素(好比類、方法、屬性、字段、結構、枚舉、組件等)的行爲信息的聲明性標籤。
AttributeUsage:描述如何使用自定義的Attribute類,規定了能夠應用到的程序中的元素類型。
Conditional:對方法或者屬性增長一個條件標記,依賴於指定的預約義是否存在。
Obsolete:標註過期的元素,不該該被使用。spa
下面是具體的使用例子,經過定義一個新的Attribute類來講明分析。code
#define TestAttribute using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Reflection; namespace StudyCSharpConsole { //AttributeUsage:用來限制和描述自定義Attribute類,規定了Attribute類適用的應用範圍。 //下面指明:適用於類和方法,只容許指定一個Attribute實例,沒法由派生類和重寫成員繼承。 //後兩個是可選的,默認設定爲false。 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] class NewAttribute : Attribute { private string name = string.Empty; private string version = string.Empty; private int count = 0; public string Name { get { return name; } set { name = value; } } public string Version { get { return version; } set { version = value; } } public int Count { get { return count; } set { count = value; } } } [New(Name = "TestClass", Version = "1.0.0", Count = 1)] class TestClass { [Conditional("TestAttribute")] public void TestMethod() { Console.WriteLine("TestMethod is run."); } [New(Name = "TestMethod2", Version = "1.0.1", Count = 2)] public void TestMethod2() { Console.WriteLine("TestMethod2 is run."); } //標註該方法不推薦使用,在調用處編譯器當作錯誤處理(false的時候當作警告) [Obsolete("TestMethod3 is Obsolete.", true)] public void TestMethod3() { Console.WriteLine("TestMethod3 is run."); } } class Program { static void Main(string[] args) { TestClass testClass = new TestClass(); //此處會報相似於後面的編譯錯誤(「TestMethod3()」已過期:「TestMethod3 is Obsolete.」)。 //testClass.TestMethod3(); //預約義了TestAttribute的場合,下面的方法會被調用,不然會忽略該方法的調用。 testClass.TestMethod(); //取得類的特性信息 NewAttribute attr = (NewAttribute)Attribute.GetCustomAttribute(typeof(TestClass), typeof(NewAttribute)); Console.WriteLine(attr.Name + "," + attr.Version + "," + attr.Count); //先取得類的方法列表 MethodInfo[] methods = typeof(TestClass).GetMethods(); foreach (MethodInfo method in methods) { //取得每一個方法的特性並顯示。 NewAttribute methodAttr = (NewAttribute) Attribute.GetCustomAttribute(method, typeof(NewAttribute)); if (methodAttr == null) { continue; } Console.WriteLine(methodAttr.Name + "," + methodAttr.Version + "," + methodAttr.Count); } } } }