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.
精彩评论