一、特性概念
特性是一种允许我们向程序的程序集添加元数据的语言结构,它是用于保存程序结构信息的某种特殊类型的类。特性提供功能强大的方法以将声明信息与 C# 代码(类型、方法、属性等)相关联。特性与程序实体关联后,即可在运行时使用反射查询特性信息。特性的目的是告诉编译器把程序结构的某组元数据嵌入程序集中,它可以放置在几乎所有的声明中(类、变量、函数等等申明)。从而实现类似"标签"、"注解"或"配置"的功能。
二、自定义特性
继承特性基类 Attribute ,一般把特性类都写成xxAttribute。使用时只用xx即可。
cs
class MyCustomAttribute : Attribute
{
public string info;
public MyCustomAttribute(string info)
{
this.info = info;
}
public void TestFun()
{
Console.WriteLine("特性的方法");
}
}
三、特性的使用
特性名(参数列表) 写在类、函数、变量上一行,表示他们具有该特性信息
本质上 就是在调用特性类的构造函数
cs
[MyCustom("这个是我自己写的一个用于计算的类")]
class MyClass
{
[MyCustom("这是一个成员变量")]
public int value;
public void TestFun(int a)
{
}
}
四、限制自定义特性的使用范围
通过为特性类 加特性 限制其使用范围
cs
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true, Inherited = true)]
参数一:AttributeTargets ------ 特性能够用在哪些地方
参数二:AllowMultiple ------ 是否允许多个特性实例用在同一个目标上
参数三:Inherited ------ 特性是否能被派生类和重写成员继承
五、系统自带特性
(1)过时特性 Obsolete
cs
[Obsolete("xxx方法已经过时了,请使用yyy方法", false)]
参数一:调用过时方法时 提示的内容
参数二:true-使用该方法时会报错 false-使用该方法时直接警告
(2)调用者信息特性 需要引用命名空间 using System.Runtime.CompilerServices;
cs
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);
}
写在函数的参数列表中,并要赋值空
CallerFilePath特性,哪个文件调用?CallerLineNumber特性,哪一行调用?
CallerMemberName特性 哪个函数调用?
调用时,不需要传入特性,编译器自动填充
(3)条件编译特性 Conditional
它会和预处理指令 #define配合使用,需要引用命名空间using System.Diagnostics;
主要可以用在一些调试代码上
(4)外部Dll包函数特性
DllImport 需要引用命名空间 using System.Runtime.InteropServices
用来标记非.Net(C#)的函数,表明该函数在一个外部的DLL中定义。
一般用来调用 C或者C++的Dll包写好的方法
六、判断是否使用了某个特性
cs
MyClass mc = new MyClass();
Type t = mc.GetType();
if( t.IsDefined(typeof(MyCustomAttribute), false) )
{
Console.WriteLine("该类型应用了MyCustom特性");
}
object[] array = t.GetCustomAttributes(true);
t.IsDefined(typeof(MyCustomAttribute), false)
参数一:特性的类型
参数二:代表是否搜索继承链(属性和事件忽略此参数)