特性
文章目錄
- 1、特性概念
- 2、自定義特性 Attribute
- 3、特性的使用
- 4、限制自定義特性的使用范圍
- 5、系統自帶特性
- 1、過時特性
- 2、調用者信息特性
- 3、條件編譯特性
- 4、外部dll包函數特性
1、特性概念
特性是一種允許我們向程序的程序集添加元數據的語言結構
它是用于保存程序機構信息的某種特殊類型的類特性本質是個類
可以利用特性類為元數據添加額外信息
比如一個類、成員變量、成員方法等為它們添加更多額外信息
之后可以通過反射來獲取這些額外信息
2、自定義特性 Attribute
繼承特性基類 Attributeclass MyCustomAttribute : Attribute{public string info;public MyCustomAttribute(string info){this.info = info;}public void TestFun(){Console.WriteLine("特性的方法");}}
3、特性的使用
基本語法:
[特性名(參數列表)]
本質上就是在調用特性類的構造函數
寫在類、函數、變量的上一行,表示他們具有該特性信息//特性的使用
MyClass myClass = new MyClass();
Type type = myClass.GetType();//判斷是否使用了某個特性
//參數一:特性的類型
//參數二:代表是否搜索繼承鏈(屬性和事件忽略此參數)
if (type.IsDefined(typeof(MyCustomAttribute), false))
{Console.WriteLine("這個類使用了MyCustom特性");
}//獲取Type元數據中的所有特性
object[] array = type.GetCustomAttributes(true);
for (int i = 0; i < array.Length; i++)
{if (array[i] is MyCustomAttribute){Console.WriteLine((array[i] as MyCustomAttribute).info);(array[i] as MyCustomAttribute).TestFun();}}聲明特性
[MyCustom("類")]
class MyClass
{[MyCustom("成員變量")]public int value;[MyCustom("成員方法")]public void TestFun([MyCustom("函數參數")] int a){}
}
4、限制自定義特性的使用范圍
//通過為特性類 加特性 限制其使用范圍
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true, Inherited = true)]
//參數一:AttributeTargets —— 特性能夠用在哪些地方
//參數二:AllowMultiple —— 是否允許多個特性實例用在同一個目標上
//參數三:Inherited —— 特性是否能被派生類和重寫成員繼承
public class MyCustom2Attribute : Attribute{}
5、系統自帶特性
1、過時特性
//過時特性
//Obsolete
//用于提示用戶 使用的方法等成員已經過時 建議使用新方法
//一般加在函數前的特性class TestClass
{//參數一:調用過時方法時 提示的內容//參數二:true報錯 false警告[Obsolete("OldSpeak方法已經過時了,請使用Speak方法", false)]public void OldSpeak(string str){Console.WriteLine(str);}public void Speak(){}public void SpeakCaller(string str, [CallerFilePath]string fileName = "", [CallerLineNumber]int line = 0, [CallerMemberName]string target = ""){Console.WriteLine(str);Console.WriteLine(fileName);Console.WriteLine(line);Console.WriteLine(target);}
}
2、調用者信息特性
哪個文件調用CallerFilePath特性
哪一行調用CallerLineNumber特性
哪個函數調用CallerMemberName特性//需要引用命名空間 using System.Runtime.CompilerServices;
//一般作為函數參數的特性
3、條件編譯特性
條件編譯特性
Conditional
它會和預處理指令 #define配合使用//需要引用命名空間using System.Diagnostics;
//主要可以用在一些調試代碼上#define Fun
[Conditional("Fun")]
static void Fun(){}
4、外部dll包函數特性
DllImport
用來標記非.Net(C#)的函數,表明該函數在一個外部的DLL中定義。
一般用來調用 C或者C++的Dll包寫好的方法
//需要引用命名空間 using System.Runtime.InteropService[DllImport("Test.dll")]static extern int Add(int a,int b);