有没有办法找到给定类型的所有属性,而无需在.Net中将BrowsableAttribute显式设置为 Yes?
我尝试了以下代码但没有成功(默认情况下可浏览的所有属性也会返回):
PropertyDescriptorCollection browsableProperties = TypeDescriptor.GetProperties(type, new Attribute[] { BrowsableAttribute.Yes });
有没有办法找到给定类型的所有属性,而无需在.Net中将BrowsableAttribute显式设置为 Yes?
我尝试了以下代码但没有成功(默认情况下可浏览的所有属性也会返回):
PropertyDescriptorCollection browsableProperties = TypeDescriptor.GetProperties(type, new Attribute[] { BrowsableAttribute.Yes });
一点反思和 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));
}