在 C# 中并没有一个专门的“获取特性的接口”即没有类似IGetAttribute这样的接口供你实现或调用。获取特性Attributes是通过反射Reflection机制完成的主要依赖以下两个核心类/方法System.Attribute类提供了静态方法来获取特性。System.Reflection命名空间下的类型如Type,MethodInfo,PropertyInfo等它们提供了实例方法GetCustomAttributes。以下是获取特性的三种主要方式1. 使用Attribute.GetCustomAttribute(推荐用于获取单个)这是最传统且语义清晰的方法适用于当你确定只需要获取一个特定类型的特性时。位置System命名空间特点如果找到返回该特性实例找不到返回null。如果同一元素上有多个同类特性且AllowMultipletrue它只返回第一个。using System; using System.Reflection; // 假设 MyClass 上有一个 [MyAttribute] Type type typeof(MyClass); // 获取单个特性 var attr (MyAttribute)Attribute.GetCustomAttribute(type, typeof(MyAttribute)); if (attr ! null) { Console.WriteLine(attr.Description); }泛型版本 (.NET Core / .NET 5 更常用):// 语法更简洁无需强制转换 var attr Attribute.GetCustomAttributeMyAttribute(type);2. 使用MemberInfo.GetCustomAttributes(推荐用于获取多个)这是Type,MethodInfo,PropertyInfo等反射对象的实例方法。适用于需要获取所有特性或者不确定是否有多个同名特性的情况。位置System.Reflection命名空间特点返回一个数组 (object[]或T[])。using System; using System.Reflection; using System.Linq; Type type typeof(MyClass); // 获取该类型上所有的 MyAttribute 实例 var attrs type.GetCustomAttributesMyAttribute(inherit: true).ToArray(); foreach (var attr in attrs) { Console.WriteLine(attr.Description); } // 如果不指定泛型返回 object[] var allAttrs type.GetCustomAttributes(inherit: true);3. 使用ICustomAttributeProvider接口 (底层机制)虽然你通常不直接使用它但值得了解的是所有可以应用特性的元素如Type,Assembly,MethodInfo都实现了System.Reflection.ICustomAttributeProvider接口。这个接口定义了两个核心方法上述的GetCustomAttributes方法本质上就是调用这里object[] GetCustomAttributes(bool inherit)object[] GetCustomAttributes(Type attributeType, bool inherit)示例通常不需要这样写除非你在做非常底层的反射框架// Type 类实现了 ICustomAttributeProvider ICustomAttributeProvider provider typeof(MyClass); var attrs provider.GetCustomAttributes(typeof(MyAttribute), true);关键参数说明inherit在调用GetCustomAttributes时通常会看到一个bool inherit参数true: 不仅检查当前元素还会沿着继承链向上查找基类或基接口上的特性前提是特性定义时[AttributeUsage(Inherited true)]。false: 只检查当前元素直接声明的特性。现代 C# 模式匹配写法 (C# 7.0)在实际开发中结合is模式匹配可以让代码更简洁var method typeof(MyClass).GetMethod(DoWork); // 检查并获取 if (method.GetCustomAttributeObsoleteAttribute() is ObsoleteAttribute obsAttr) { Console.WriteLine($该方法已过时: {obsAttr.Message}); } // 或者检查是否存在任意特性 if (method.GetCustomAttributesAuthorizationAttribute().Any()) { // 执行授权逻辑 }总结需求推荐方法返回类型获取单个特定特性Attribute.GetCustomAttributeT(member)T(找不到为 null)获取所有特定特性member.GetCustomAttributesT()IEnumerableT获取所有特性(不限类型)member.GetCustomAttributes()object[]底层接口ICustomAttributeProviderobject[]注意为了性能考虑.NET 6 及更高版本引入了System.Reflection.CustomAttributeExtensions上述泛型方法大多扩展自此类性能优于旧的非泛型方法。