开发者

How to determine whether an interface type implements a custom attibute

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜