开发者

How to determine whether an interface type implements a custom attibute

开发者 https://www.devze.com 2023-01-08 17:18 出处:网络
H开发者_C百科ow to determine whether an interface type implements a custom attibute?Use GetCustomAttributes:

H开发者_C百科ow to determine whether an interface type implements a custom attibute?


Use GetCustomAttributes:

typeof(IWhatever).GetCustomAttributes(typeof(CustomAttribute), false)

Will return an array of attributes. Empty if it doesn't implement the one you're searching for.


Try this on for size:

private static bool HasAttribute(this Type me, Type attribute)
{
    if (!typeof(Attribute).IsAssignableFrom(attribute))
        throw new ArgumentException("attribute does not extend System.Attribute.");
    return me.GetCustomAttributes(attribute, true).Length > 0;
}
private static bool HasAttribute<T>(this Type me) where T : System.Attribute
{
    return me.HasAttribute(typeof(T));
}


Type iType = typeof(IMyInterface);
var attributes = iType.GetCustomAttributes(typeof(MyCustomAttribute), true);

If attributes is empty, then the Interface doesn't implement your attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消