如何知道为类型定义的属性? [英] How to know the attributes defined for a type?
本文介绍了如何知道为类型定义的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经定义了一个自定义属性,并将其添加到了几个类中.知道我正在使用反射来捕获程序集中的所有类型.我只想过滤出已定义此属性的类型.
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.
我已经看到Type对象的Attributes
属性,但是它仅返回
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?
推荐答案
您可以这样做:
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)
这篇关于如何知道为类型定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文