在.Net中查找没有BrowsableAttribute明确设置为Yes的所有属性

时间:2014-08-05 10:16:07

标签: .net typedescriptor browsable

有没有办法找到给定类型的所有属性,而{。}}在.Net中没有明确设置为是?

我尝试了以下代码但没有成功(默认情况下也可以浏览所有属性):

PropertyDescriptorCollection browsableProperties = TypeDescriptor.GetProperties(type, new Attribute[] { BrowsableAttribute.Yes });

1 个答案:

答案 0 :(得分:1)

有点反思和linq会有所帮助。

var result =  type
    .GetProperties()
    .Where(x =>
            x.GetCustomAttribute<BrowsableAttribute>() == null ||
            !x.GetCustomAttribute<BrowsableAttribute>().Browsable)
    .ToList();

您可以引入局部变量以避免两次调用GetCustomAttribute方法。

如果您的.Net框架版本低于4.5,您可以编写自己的GetCustomAttribute扩展方法,如下所示

public static T GetCustomAttribute<T>(this MemberInfo element) where T: Attribute
{
    return (T) element.GetCustomAttribute(typeof(T));
}
相关问题