【问题标题】:Find all properties without BrowsableAttribute explicitely set to Yes in .Net在.Net中查找所有没有明确设置为“是”的可浏览属性的属性
【发布时间】:2014-08-05 10:16:07
【问题描述】:

有没有办法在.Net 中不将BrowsableAttribute 明确设置为“是”的情况下查找给定类型的所有属性?

我尝试了以下代码,但没有成功(所有默认可浏览的属性也都返回了):

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

【问题讨论】:

  • 这有点宽泛..您在寻找什么答案?你看过 PropertyInfo、Reflection 什么的吗?简短的回答可能是“是”,这是您想知道的吗?
  • 欢迎任何答案 :) 如果有帮助,我会用我尝试过的方法更新我的问题
  • 嗯,例如,定义您希望从给定类中获得的预期结果将极大地帮助增加问题的约束,并为未来的读者添加信息。

标签: .net typedescriptor browsable


【解决方案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));
}

【讨论】:

  • 谢谢,有一些错误(它是 GetCustomAttributes,不是 GetCustomAttribute,而且它缺少演员表),但我明白了,它完成了工作!
  • @GyumFox 还有一个版本的GetCustomAttribute
  • PropertyInfo 没有 GetCustomAttribute 方法,但您正在使用该方法
  • 哎呀,我没看到扩展方法
  • 看起来 GetCustomAttribute 只能从 .NET 4.5 开始使用
猜你喜欢
  • 1970-01-01
  • 2016-01-11
  • 2015-03-29
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多