C#高级语法之特性

自定义特性和使用


什么是特性

特性(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()​ 可以获取类所使用的自定义的特性

调用者信息特性


static void ShowMessage(string message, [CallerLineNumber] int lineNumber = 0, [CallerFilePath] string filePath = "")
{
  
}
  • [CallerLineNumber]​ : 调用该方法的行号
  • [CallerFilePath]​ :调用者的文件路径
  • [CallerMemberName]​ :调用者的名称
  • 以上特性需要在形参列表中使用,且在使用时必须给定初始值

Obsolete 特性


[Obsolete]
static void Test()
{

}
  • [Obsolete]​ 特性:弃用

  • Obsolete​ 标注的方法为弃用的方法,被标注的方法仍然可以使用,但不推荐

  • 还可以在使用特性时传递提示信息,如:

    [Obsolete("该方法已弃用,请使用最新的NewTest方法")]
    
  • Obsolete​ 特性的第二个参数是 bool​ 类型,为 true​ 时使用被标记的方法会报错;为 false​ 时不会,默认为 false

DebuggerStepThrough 特性


[DebuggerStepThrough]
static void Test()
{
  
}
  • [DebuggerStepThrough]​ :在调试时会跳过被该特性修饰的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值