如何知道为类型定义的属性?

时间:2012-08-23 12:45:05

标签: c# .net reflection attributes

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

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

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

1 个答案:

答案 0 :(得分:6)

你可以这样做:

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();
    }
}

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