【问题标题】:How to know the attributes defined for a type?如何知道为类型定义的属性?
【发布时间】:2012-08-23 12:45:04
【问题描述】:

我已经定义了一个自定义属性并将其添加到几个类中。知道我正在使用反射来捕获程序集中的所有类型。我只想过滤掉定义了这个属性的类型。

我已经看到了 Type 对象的 Attributes 属性,但它只返回 specific enum 中包含的值。

如何检索定义了自定义属性的类型?

【问题讨论】:

标签: c# .net reflection attributes


【解决方案1】:

你可以这样做:

object[] attributes = typeof(SomeType).GetCustomAttributes(typeof(YourAttribute), true);

但我更喜欢使用自定义扩展方法:

public static class ReflectionExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider obj, bool inherit)
        where TAttribute : Attribute
    {
        return obj.GetAttributes<TAttribute>(inherit).FirstOrDefault();
    }

    public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this ICustomAttributeProvider obj, bool inherit)
        where TAttribute : Attribute
    {
        return obj.GetCustomAttributes(typeof (TAttribute), inherit).Cast<TAttribute>();
    }

    public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider obj, bool inherit)
        where TAttribute : Attribute
    {
        return obj.GetAttributes<TAttribute>(inherit).Any();
    }
}

(它们也适用于程序集、方法、属性等,而不仅仅是类型)

【讨论】:

  • 真丢脸,我怎么会错过呢? :o
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 2012-11-04
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多