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

Ant*_*ine 1 .net c# reflection attributes

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

我已经看到Attributes了Type对象的属性,但它只返回特定枚举中包含的值.

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

Tho*_*que 6

你可以这样做:

object[] attributes = typeof(SomeType).GetCustomAttributes(typeof(YourAttribute), true);
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

(它们也适用于装配,方法,属性等,而不仅仅适用于类型)