個人定義:不侵入對象的情況下,添加對象附注信息。
官方定義:將預定義的系統信息或用戶定義的自定義信息與目標元素相關聯。目標元素可以是程序集、類、構造函數、委托、枚舉、事件、字段、接口、方法、可移植可執行文件模 ? 塊、參數、屬性 (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
?