自定义 Attribute 是 C# 中实现元数据标注和运行时反射的关键能力,它让代码具备“自我描述”能力,常用于权限控制、序列化配置、日志记录、API 文档生成等场景。核心在于继承 Attribute 类,并合理使用 AttributeUsage 控制其适用范围。
一、定义一个基础自定义特性
只需新建一个类,继承 Attribute,并用 [AttributeUsage] 明确它能标记哪些程序元素(如类、方法、属性等):
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] —— 表示该特性可应用于类或方法,不允许重复添加,且子类可继承 构造函数通常用于必填参数(位置参数),属性用于可选参数(命名参数)示例:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiVersionAttribute : Attribute
{
public ApiVersionAttribute(string version) => Version = version;
public string Version { get; }
public bool IsDeprecated { get; set; } = false;
}二、在代码中应用特性
直接写在目标成员上方,支持位置参数(构造函数传入)和命名参数(属性赋值):
[ApiVersion("v2.1")] → 调用带参构造 [ApiVersion("v3.0", IsDeprecated = true)] → 构造 + 属性赋值 可同时标注多个不同特性,也可(若 AllowMultiple=true)重复标注同一特性例如:
[ApiVersion("v2.1")]
public class UserController { }
<p>[ApiVersion("v3.0", IsDeprecated = true)]
public void GetUsers() { }三、在运行时读取特性信息
借助 GetCustomAttribute 或 GetCustomAttributes 方法,配合反射使用:
获取类上的特性:typeof(UserController).GetCustomAttribute() 获取方法上的特性:typeof(UserController).GetMethod("GetUsers").GetCustomAttribute() 检查是否存在:Attribute.IsDefined(typeof(UserController), typeof(ApiVersionAttribute))典型用法(比如 API 版本路由前检查):
var attr = method.GetCustomAttribute<ApiVersionAttribute>();
if (attr != null && attr.IsDeprecated)
{
throw new NotSupportedException($"API {method.Name} is deprecated.");
}四、进阶技巧与注意事项
特性类的字段/属性必须是 public,且类型限于:基本类型、string、Type、其他 Attribute、以上类型的数组 避免在特性中放复杂逻辑或耗时操作——特性本质是静态元数据,应在使用处(如中间件、AOP 拦截器)处理业务 若需编译期校验(如要求某特性必须存在),可用 Source Generator 或 Roslyn 分析器扩展 注意 Inherited = false 时,子类不会继承父类上的特性(对虚方法重写也适用)基本上就这些。自定义 Attribute 不复杂但容易忽略细节,关键是想清楚“谁来用它”和“什么时候读它”。写好之后,搭配反射或框架扩展点(如 ASP.NET Core 的 IAuthorizationFilter、IActionFilter),就能解锁大量自动化能力。
