C# 自定义特性Attribute

一、特性Attribute和注释有什么区别

特性Attribute

  A:就是一个类,直接继承/间接继承Attribute

  B:特性可以在后期反射中处理,特性本身是没有什么*用的

  C:特性会影响编译和运行时功能

注释

  A:就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性

  B:注释不能后期处理

二、自定义Attribute特性的使用

自定义Attribute特性的语法

//直接继承Attribute
public class CustomAttribute : Attribute
{
    public string Name { get; set; }

    public CustomAttribute()
    {
        Console.WriteLine($"{this.GetType().Name} 无参构造函数");
    }

    public CustomAttribute(string name)
    {
        Console.WriteLine($"{this.GetType().Name} string 参数构造函数");
        Name = name;
    }
}

//间接继承Attribute
public class CustomAttributeChild : CustomAttribute
{
    public CustomAttributeChild()
    {
        Console.WriteLine($"{this.GetType().Name} 无参构造函数");
    }

    public CustomAttributeChild(string name) : base(name)
    {
        Console.WriteLine($"{this.GetType().Name} string 参数构造函数");
    }
}

猜你喜欢

转载自www.cnblogs.com/Ramon-Zeng/p/10150739.html