自定义特性和使用

自定义特性和使用


什么是特性

特性(attribute)是一种允许我们向程序的程序集增加元数据的语言结构,它是用于保存程序结构信息的某种特殊类型的类。

  • 将应用了特性的程序结构叫做目标
  • 设计用来获取和使用元数据的程序(对象浏览器)叫做特性的消费者
  • .NET 预定了很多特性,我们也可以声明自定义特性

创建自定义特性

创建特性其实就是创建特性类,特性类的命名必须以 Attribute 结尾

[AttributeUsage(AttributeTargets.Class)]
public sealed class InformationAttribute : Attribute
{
    public string developer;
    public string version;
    public string description;

    public InformationAttribute(string developer, string version, string description)
    {
        this.developer = developer;
        this.version = version;
        this.description = description;
    }
}
  • 特性类需要继承 Attribute​ 类
  • 特性类需要添加 sealed​ 关键字,表示该类不能被继承
  • [AttributeUsage(AttributeTargets.Class)]​ 表示该特性需要应用于类

自定义特性的使用

[Information("tkzc", "v1.0", "这个类是用来....的类")]
internal class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(Program);
        bool result = t.IsDefined(typeof(InformationAttribute), false);
        Console.WriteLine(result); // True

        Object[] attributeArray = t.GetCustomAttributes(false);
    }
}
  • 使用特性其实就是调用特性类的构造方法
  • 使用 t.GetCustomAttributes()​ 可以获取类所使用的自定义的特性
posted @ 2023-10-04 14:48  天空之城00  阅读(18)  评论(0)    收藏  举报