我定义了一个自定义属性并将其添加到几个类中。知道我正在使用反射来捕获程序集中的所有类型。我只想过滤掉定义了该属性的类型。
我见过 Type 对象的 Attributes
属性,但它只返回 specific enum 中包含的值.
如何检索定义了自定义属性的类型?
最佳答案
你可以这样做:
object[] attributes = typeof(SomeType).GetCustomAttributes(typeof(YourAttribute), true);
但我更喜欢使用自定义扩展方法:
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();
}
}
(它们也适用于程序集、方法、属性等,而不仅仅是类型)
关于c# - 如何知道为类型定义的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12091900/