特性
特性
特性是一种允许我们向程序的程序集添加元数据的语言结构
特性本质是一个类,可以利用特性类为元数据添加额外信息
自定义特性
//继承特性基类
class MyCustomAttribute : Attribute
{
//特性中的成员,一般根据需求来写
public string info;
public MyCustomAttribute(string info)
{
this.info = info;
}
public void TestFun()
{
}
}
特性的使用
//基本语法:
//[特姓名(参数列表)]
//本质上就是再调用特性类的构造函数
//写在类,函数,变量上一行来表示它们具有该特性信息
[MyCustom("1234")]
class MyClass
{
[MyCustom("1234")]
public int value;
[MyCustom("2345")]
public void TestFun([MyCustom("1234")]int a )
{
}
}
MyClass mc = new MyClass();
Type t =mc.GetType();
//判断是否使用了某个特性
//参数1:特性的类型
//参数2:是否搜索继承链(属性和事件忽略此参数)
if(t.IsDefined(typeof(MyCustomAttribute),false))
{
Console.WriteLine("该类型应用了MyCustom特性");
}
//获取Type元数据中所有特性
object[] array = t.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();
}
}
限制自定义特性的适用范围
//通过为特性类加特性就可限制其适用范围
//参数一:AttributeTargets特性能用在哪些地方
//参数二:AllowMultiple是否允许多个特性实例用在同一个目标上
//参数三:Inherited特性是否能被派生类和重写成员继承
[AttributeUsage(AttributeTargets.Class|AttribbuteTargets.Struct,AllowMultiple = true,
Inherited = true)]
public class MyCustom2Attribute : Attribute
{
}
系统自带特性
//过时特性 Obsolete
//用于提示用户使用的方法等成员已经过时,建议使用新方法
//一般加载函数前
//参数一:调用过时方法时提示的内容
//参数二:true-使用该方法时会报错 false-使用该方法时会警告
class TestClass
{
[Obsolete("Oldspeak方法已经过时,请使用新方法",false)]
public void OldSpeak()
{
}
public void Speak()
{
}
//调用者信息特性
//CallerFilePath 哪个文件调用
//CallerLineNumber 哪一行调用
//CallerMemberName 哪个函数调用
//一般作为函数参数的特性
public void SpeakCaller(string str,[CallerFilePath]string fileName="",[CallerLineNumber]int line = 0,[CallerMemberName]string target ="")
{
}
}
//条件编译特性 Conditional
//它会和预处理指令#define配合使用
//主要可以用在一些调试代码上
//有时想执行有时不想执行的代码
//前面必须有#define Fun才会被编译
[Conditional("Fun")]
static void Fun()
{
Console.WriteLine("Fun执行");
}
//DllImport 外部Dll包函数特性
//用来标记非.Net(C#)的函数,表明该函数在一个外部的DLL中定义
//一般用来调用C或者C++的DLL包写好的方法

浙公网安备 33010602011771号