发布时间:2026-10-03 03:56:35 浏览次数:3
下面是针对“C# 特性AttributeUsage简介与使用教程”的详细讲解攻略:
C# 中的特性是一种引用元数据的方式,可以给程序元素(如类、方法、属性等等)打上标记,为程序元素添加一些额外的信息。使用特性可以达到如下目的:
AttributeUsageAttribute 是 System.Attribute 层次结构的一个重要特性类。AttributeUsageAttribute 可以控制自定义特性如何使用。
AttributeUsageAttribute 类具有以下内容:
首先,使用特性需要引入 System 命名空间。在此命名空间中,我们可以调用 Attribute 类,该类是所有特性类的父类。
AttributeUsageAttribute 是属性,因此使用它时,应将其放在其他自定义特性类的声明之前。通过使用 AttributeUsageAttribute,我们可以指定特性的目标元素。例如:
using System;[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]public class MyClassAttribute : Attribute{ public string Author {get; set;} public double Version { get; set; } public MyClassAttribute(string author) { Author = author; }}在这个示例中,AttributeUsageAttribute 指定了特性的目标元素(类),并且该示例还定义了两个属性和一个构造函数。
特性使用语法格式为在元素名称前加上方括号 [],括号中加上特性类的名称,并为该类提供必要的参数。例如:
using System;[MyClass("John", Version = 1.0)]public class TestClass{ // ...}在这里,使用 MyClassAttribute 特性来给 TestClass 类打上 “John” 这个作者的标记,该类的版本号为 1.0。
再看一个具体的示例,如下所示:
using System;[AttributeUsage(AttributeTargets.Method)]public class ParamCheckAttribute : Attribute { private string desc = ""; public ParamType typeCheck = ParamType.STRING; public ParamCheckAttribute(string desc) { this.desc = desc; } public string Desc { get{ return desc;} }} public class ConsoleHello { [ParamCheck("Name should not be empty!")] private static void SayHello(string name) { if(name == null || name.Trim().Length == 0) { throw new ArgumentException("name"); } Console.WriteLine($"Hello, {name}!"); }}class Program { static void Main(string[] args) { ConsoleHello.SayHello(""); }}上面的示例中,我们定义了一个 ParamCheckAttribute 特性类,该类被定义为只在方法中使用。定义了一个方法 SayHello(),并在该方法上使用 ParamCheck 特性。ParamCheck 特性有一个构造函数和一个属性。在程序中用 SayHello() 方法调用时,使用了一个空字符串,但是 ParamCheck 特性强制该参数不能为空,因此输出了一个“ArgumentException”异常。
在这个示例中,ParamCheck 特性被用于创建自己的类型检查规则。开发人员可以使用 ParamCheck 特性去标记他们的方法和属性,并为他们增加 “描述信息”和 “检查程序”。
通过此篇文章,我们了解了 AttributeUsageAttribute 类的使用和作用,并做了两个相对实用的示例。在实际编程中又有什么好的想法呢?