標籤:
在c#中,定義類的成員,可以定義Property稱為屬性.Attribute就稱為特性.
在FCL中,有內建的Attribute.如:
Condition[Attribute]:在什麼條件可以調用.(只能作用於傳回值為void的方法上)
Obsolete:方法棄用.支援禁用.
代碼1:
class Program { static void Main(string[] args) { Func(); Console.ReadLine(); } [Obsolete("you can use Func to replace this",true)] private static void Test() { Console.WriteLine("noooo"); } private static void Func() { Console.WriteLine("yesss"); } } class T { [Conditional("DEBUG")] public static void M(string str) { Console.WriteLine("Method{0}", str); } }內建Attribute
自訂Attribute:
代碼2:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class HelpAttribute : Attribute { public HelpAttribute(string str) { HelpStr = str; } public string Name { get; set; } public string HelpStr { get; set; } }自訂Attribute
AttributeTargets.Class:作用目標只能是類.
AllowMultiple:是否可以在一個元素上多次作用特性.
Inherited:當目標被繼承時,特性是否也繼承.
反射擷取類的Attribute資訊:
代碼3:
class Program { static void Main(string[] args) { var attrs = typeof(MyClass).GetCustomAttributes(false); for (int i = 0; i < attrs.Length; i++) { var attr = attrs[i] as HelpAttribute; if (attr != null) Console.WriteLine(attr.HelpStr + attr.Name); } Console.ReadLine(); } } [Help("good", Name = " class")] class MyClass { }反射擷取特性資訊
C#文法之Attribute