標籤:als xtend using typeof ted 情況 lease des space
個人定義:不侵入對象的情況下,添加對象附註資訊。
官方定義:將預定義的系統資訊或使用者定義的自訂資訊與目標元素相關聯。目標元素可以是程式集、類、建構函式、委託、枚舉、事件、欄位、介面、方法、可攜式執行檔模 塊、參數、屬性 (Property)、傳回值、結構或其他屬性 (Attribute)。提供的資訊也稱為中繼資料,中繼資料可由應用程式在運行時進行檢查以控製程序處理資料的方式,也可以由外部工具在運行前檢查以控制應用程式處理或維護自身的方式。
.Net 架構提供了三種預定義特性:
- AttributeUsage
- Conditional
- Obsolete
樣本: 讀取枚舉值上加的 特性資訊
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyAttribute{ [Obsolete("這是一個到期特性")] public enum EnumState { [Remark("我是開啟")] //[Remark("")] Open =1, [Remark("我是關閉")] Close=2 }}
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace MyAttribute{ //1.特性的適用範圍 2.特性是否允許用多次 3.特性是否被衍生類別繼承 [AttributeUsage(AttributeTargets.All,AllowMultiple =true, Inherited =true)] //被調用時執行條件編譯,取決於指定的值(如“DEBUG”,"RELEASE"...) [Conditional("DEBUG")] public class RemarkAttribute:Attribute { public string remark; public string Remark { get { return remark; } } public RemarkAttribute(string remark) { this.remark = remark; } } public static class RemarkExtend { public static string RemarkDescription(this EnumState state) { Type type = typeof(EnumState); FieldInfo info= type.GetField(state.ToString()); object[] remarkCustomAttribute= info.GetCustomAttributes(typeof(RemarkAttribute),false); if(remarkCustomAttribute != null && remarkCustomAttribute.Length>0) { RemarkAttribute remarkattribute = remarkCustomAttribute[0] as RemarkAttribute; return remarkattribute.Remark; } else { return state.ToString(); } } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyAttribute{ class Program { static void Main(string[] args) { EnumState state = EnumState.Open; Console.WriteLine(state.RemarkDescription()); Console.Read(); } }}
至此,關於特性的學習就到此結束了,謝謝您的閱讀。
特性還有很多進階的用法,博主只是小試牛刀,希望本文能夠幫到你,當然若有不完善地方,歡迎斧正。
參考MSDN:https://msdn.microsoft.com/zh-cn/library/system.attribute(VS.80).aspx
C# 特性(Attribute)