C#的特性(Attribute)是什么?如何创建和使用自定义特性?

来源:这里教程网 时间:2026-02-21 17:31:30 作者:

特性(Attribute)是 C# 中一种为代码元素添加元数据的机制。它允许你在类、方法、属性、参数等程序元素上附加声明性信息,这些信息可以在编译时或运行时通过反射读取和处理。

例如,内置特性 [Obsolete] 可以标记某个方法已过时,编译器会给出警告:

[Obsolete("此方法已废弃,请使用 NewMethod")] void OldMethod() { }

如何创建自定义特性?

自定义特性是一个继承自 System.Attribute 的类。通常命名以 "Attribute" 结尾,但在使用时可以省略该后缀。

下面是一个简单的自定义特性的定义:

[AttributeUsage(AttributeTargets.Method)] // 限制只能用于方法 public class LogActionAttribute : Attribute { public string ActionName { get; set; }
public LogActionAttribute(string actionName)
{
    ActionName = actionName;
}

}

说明:

AttributeUsage 指定该特性可应用的目标(如类、方法、属性等)。 构造函数用于在使用特性时传入必要参数。 公共属性可用于传递额外的命名参数。

如何使用自定义特性?

定义好特性后,就可以将其应用到目标代码元素上。

class Program { [LogAction("用户登录", ActionName = "Authentication")] public static void Login() { Console.WriteLine("执行登录操作"); } }

上面代码中,[LogAction("用户登录")] 将特性附加到 Login 方法上,其中 "用户登录" 是构造函数参数,ActionName 是命名参数。

如何在运行时读取特性?

通过反射可以检查某个方法是否被特定特性标记,并获取其数据。

static void Main() { var method = typeof(Program).GetMethod("Login"); var attribute = method.GetCustomAttribute();

if (attribute != null)
{
    Console.WriteLine($"动作描述: {attribute.ActionName}");
}
// 执行方法
Login();

}

输出结果:

动作描述: Authentication 执行登录操作

这种机制常用于日志记录、权限验证、序列化控制、API 文档生成等场景。

基本上就这些。自定义特性不复杂但容易忽略细节,比如作用目标和是否允许多次使用(AllowMultiple),记得用 AttributeUsage 明确约束。

相关推荐

热文推荐