propertyInfo.GetCustomAttribute什么意思
propertyInfo.GetCustomAttribute<T>() 的意思是“从这个属性上把指定类型的自定义特性(Attribute)拿出来;如果它没贴过这个特性,就返回 null。”
更具体地说
-
propertyInfo是某个属性的反射元数据(PropertyInfo对象)。 -
GetCustomAttribute<T>是 .NET 提供的扩展方法,内部调用Attribute.GetCustomAttribute。 -
调用后得到的就是 该属性上贴了且仅贴了一个的 T 特性实例。
-
找到 → 返回那个实例
-
没找到 → 返回
null -
贴了多个 → 抛异常(此时应改用
GetCustomAttributes<T>())
-
示例代码
csharp
public class Demo
{
[Range(1, 100)]
public int Age { get; set; }
}
var prop = typeof(Demo).GetProperty(nameof(Demo.Age));
var rangeAttr = prop.GetCustomAttribute<RangeAttribute>();
if (rangeAttr != null)
{
Console.WriteLine($"Age 的合法范围是 {rangeAttr.Min} - {rangeAttr.Max}");
}
和“普通 Attribute.GetCustomAttribute”的区别
表格
| 写法 | 是否扩展方法 | 代码简洁度 |
|---|---|---|
Attribute.GetCustomAttribute(prop, typeof(RangeAttribute)) |
❌ | 较长 |
prop.GetCustomAttribute<RangeAttribute>() |
✅ | 更短、泛型 |
注意
-
需要
using System.Reflection; -
特性类本身要继承自
System.Attribute
浙公网安备 33010602011771号