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
posted @ 2025-08-22 18:11  yinghualeihenmei  阅读(24)  评论(0)    收藏  举报