特性

 
文章目录
- 1、特性概念
 - 2、自定义特性 Attribute
 - 3、特性的使用
 - 4、限制自定义特性的使用范围
 - 5、系统自带特性
 - 1、过时特性
 - 2、调用者信息特性
 - 3、条件编译特性
 - 4、外部dll包函数特性
 
1、特性概念
特性是一种允许我们向程序的程序集添加元数据的语言结构
它是用于保存程序机构信息的某种特殊类型的类
特性本质是个类
可以利用特性类为元数据添加额外信息
比如一个类、成员变量、成员方法等为它们添加更多额外信息
之后可以通过反射来获取这些额外信息
 
2、自定义特性 Attribute
继承特性基类 Attribute
    class 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);
                


















