【C#】Attribute(特性)

1、Attribute是什么?

C#中的Attribute(特性)是一种用于给程序元素(如类、方法、属性等)添加元数据的机制。Attribute可以用于为程序元素提供额外的信息,以便于编译器、运行时和其他工具进行处理和分析。特性的本质是一个从·System.Attribute基类派生的类,特性类的命名通常以Attribute结尾,使用时可以不写结尾的Attribute。

示例:
C#中预定义的ObsoleteAttribute

namespace System
{
    public sealed class ObsoleteAttribute : Attribute
    {
    	// ...
    	public ObsoleteAttribute(string? message, bool error);
    }
}
[Obsolete("使用xxx方法替代。",false)] 
class Program {
	// ...
}

Obsolete是一个Attribute(特性)类。ObsoleteAttribute是C#中一个预定义的特性类,用于标记已过时的方法、属性、类或其他程序元素。Obsolete标签可以声明该类已过时,布尔参数可以设置使用是否报错。

2、如何使用自定义Attribute?

  1. 定义一个类,直接或间接的继承Attribute父类。
  2. 类名约定俗成使用Attribute结尾,标记时类名中的Attribute会被省略。
  3. 可以标记(修饰)在类、类内部的所有元素。默认不能重复标记。

示例:

class TestAttribute : Attribute { } // 定义TestAttribute特性类
 // 使用TestAttribute特性
[Test] // 修饰Program类
class Program {
    [Test] private string name;// 修饰name属性
    [Test] // 修饰GetName方法
    [return:Test] // 修饰返回值
    public string GetName([Test] int index) { // 修饰参数index
        return this.name;
    }
}

我们自定义了TestAttribute 特性类,并修饰了Program类以及类内部的属性、方法、方法的返回值和参数。此外还可以修饰结构、枚举、组件等。

3、约束特性

在自定义Attribute特性类时,可以使用AttributeUsage特性进行修饰,其中第一个参数AttributeTargets是用来约束特性的标记范围,第二个参数AllowMultiple 使特性可重复标记。

示例:

// 声明特性约束
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple = true)]
class TestAttribute : Attribute { } // 定义TestAttribute特性类

上面的TestAttribute 特性类经过约束后只能修饰类和方法,并且可重复修饰。

4、使用反射调用特性

在C#中,可以使用反射来调用特性(Attribute)。
示例:

[Test("Hello world")]
class TestProgram  { }
class TestAttribute : Attribute
{
	public string message;
	public TestAttribute(string message) {
		this.message = message;
	}
}

接下来使用反射将message的内容打印出来

Type type = typeof(TestProgram);

// 检查TestProgram上是否存在TestAttribute
bool hasAttribute = type.IsDefined(typeof(TestAttribute), false);

if (hasAttribute)
{
    // 获取TestProgram上的TestAttribute的值
    TestAttribute attribute = (TestAttribute)type.GetCustomAttributes(typeof(TestAttribute), false).FirstOrDefault();
    // 使用获取到的属性值
    if (attribute != null)
    {
        string value = attribute.message;
        Console.WriteLine(value); // 输出:Hello World
    }
}

关于C#中的特性Attribute暂时先了解到这。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值