1.什么是特性
特性是一种允许我们向程序的程序集增加元数据的语言结构。他是用于保存程序结构信息的某种特殊类型的类。
- 设计用来获取和使用元数据的程序(对象浏览器)叫做特性的消费者
- .NET预定了很多特性,我们也可以声明自定义特性
- 将应用了特性的程序结构叫做目标
2.声明自定义特性
声明一个特性类和声明其他特性类一样,有下面的注意事项
- 声明一个派生自System.Attribute的类
- 给他起一个以后缀Attribute结尾的名字
例如定义一个特性类
[AttributeUsage(AttributeTargets.Class)] //特性:定义使用目标 --> class
internal sealed class InformationAttribute:Attribute
{
public string developer;
public string version;
public string desciption;
public InformationAttribute(string developer, string version, string desciption)
{
this.developer = developer;
this.version = version;
this.desciption = desciption;
}
}
在另一个类的函数下使用特性
[Information("sino","v1.1","发射核弹")]
internal class Program
{
static void Main(string[] args)
{
Type t = typeof(Program);
//打印特性信息
bool result = t.IsDefined(typeof(InformationAttribute), false);
Console.WriteLine(result);
object[] attributeArray = t.GetCustomAttributes(false);
Console.ReadKey();
}
}