在C#中,特性(Attributes)是一種向程序元素(如類、方法、屬性等)添加元數據的方式。特性可以用來提供關于程序元素的附加信息,這些信息可以在編譯時和運行時被訪問。
特性主要有以下幾個用途:
-
提供元數據:特性可以提供關于類、方法、屬性等的附加信息,這些信息可以被編譯器、運行時環境或其他工具使用。
-
標記程序元素:特性可以用來標記程序元素,以便在編譯時或運行時進行特定的處理。例如,使用
[Obsolete]
特性可以標記一個方法或類為已過時。 -
自定義行為:開發者可以創建自定義特性,以提供特定的行為或功能。例如,通過自定義特性,可以在運行時動態地改變程序的行為。
-
支持反射:特性與反射緊密集成,使得程序可以在運行時查詢和使用特性提供的信息。
-
簡化代碼:使用特性可以簡化代碼,避免重復代碼,提高代碼的可維護性和可讀性。
C#中一些常用的內置特性包括:
-
[Obsolete]
:用于標記類、方法、屬性等為已過時,如果代碼中使用了這些元素,編譯器會發出警告。 -
[Serializable]
:指示一個類可以被序列化,這對于跨應用程序域或網絡傳輸對象非常有用。 -
[AttributeUsage]
:定義自定義特性的使用方式,例如它可以應用于類、方法或屬性。 -
[Flags]
:用于標記枚舉,表示枚舉可以作為一組標志來使用,通常與位運算結合使用。 -
[Conditional]
:用于條件編譯,只有當定義了特定的預處理器符號時,標記的方法才會被調用。
using System.Diagnostics; ? namespace _7._14day01 {internal class Program{static void Main(string[] args){UserClass userClass = new UserClass();userClass.print(); ?}?}public class UserClass{[DebuggerStepThrough]public ?void print(){ ?Console.WriteLine("這個方法很簡單");}} } ?
能夠直接跳過該方法的Debug
using System.Diagnostics; ? namespace _7._14day01 {internal class Program{static void Main(string[] args){UserClass userClass = new UserClass();userClass.print(); ?}?}public class UserClass{[Obsolete("1111", true)]public ?void print(){ ?Console.WriteLine("這個方法很簡單");}} } ?
當將[Obsolete]標記為true時 如果使用該類 系統會報錯
使用的地方
幾乎所有的框架都用到了,MVC---WebApi----EF-----IOC----AOP
特性的使用場景:可以用來做數據驗證。
特性分類
第一種C#自帶
第二種 自定義
使用方法如下
using System.Diagnostics; ? namespace _7._14day01 {internal class Program{static void Main(string[] args){//UserClass userClass = new UserClass();//userClass.print();//UseAttribute useAttribute = new UseAttribute();AttributeTest attributeTest = new AttributeTest();attributeTest.Test(); ?} ? ?} ?class AttributeTest{public void Test(){Type type = typeof(UseAttribute);object[] obj = type.GetCustomAttributes(true);foreach (object customArributes in obj){DefindAttribute defindAttribute = customArributes as DefindAttribute;if(defindAttribute != null){Console.WriteLine(defindAttribute.Showinfo);}}}} ?[DefindAttribute("調用了這個特性DefindAttribute")]class UseAttribute{ ? ? ?}class DefindAttribute : Attribute{public DefindAttribute(string showinfo){Showinfo = showinfo; ?}public string Showinfo { get; set; }} ? ? } ?