How to know the attributes defined for a type?

2019-08-06 01:38发布

问题:

I have defined a custom attribute and added it to a few classes. Know I'm using reflection to capture all types in the assembly. I want to filter out only the type that have this attribute defined.

I've seen the Attributes property for a Type object, but it returns only the values contained in a specific enum.

How can I retrieve types having a custom attribute defined?

回答1:

You can do that:

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

But I prefer to use custom extension methods:

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

(they work also for assemblies, methods, properties, etc, not just for types)