【问题标题】:Get all properties of Browsable attribute获取 Browsable 属性的所有属性
【发布时间】:2015-02-11 15:11:11
【问题描述】:

我有一个类,它有很多属性,有些属性有Browsable 属性。

public class MyClass
{
    public int Id;
    public string Name;
    public string City;

    public int prpId
    {
        get { return Id; }
        set { Id = value; }
    }

    [Browsable(false)]
    public string prpName
    {
        get { return Name; }
        set { Name = value; }
    }

    [Browsable(true)]
    public string prpCity
    {
        get { return City; }
        set { City= value; }
    }
}

现在使用Reflection,如何过滤具有Browsable attributes 的属性?在这种情况下,我只需要获取prpNameprpCity

这是我目前尝试过的代码。

 List<PropertyInfo> pInfo = typeof(MyClass).GetProperties().ToList();

但这会选择所有属性。有没有办法过滤只有Browsable attributes 的属性?

【问题讨论】:

  • 您想要所有具有可浏览性的属性,对吗?或者只是那些带有 Browsable(true) 的?
  • 所有可浏览@Selman22的属性

标签: c# properties attributes system.reflection


【解决方案1】:

要仅包含具有[Browsable(true)] 的成员,您可以使用:

typeof(MyClass).GetProperties()
               .Where(pi => pi.GetCustomAttributes<BrowsableAttribute>().Contains(BrowsableAttribute.Yes))
               .ToList();

【讨论】:

  • 如何获取标记为可浏览的列的值为false。
【解决方案2】:

您可以使用Attribute.IsDefined 方法检查Browsable 属性是否定义在属性中:

typeof(MyClass).GetProperties()
               .Where(pi => Attribute.IsDefined(pi, typeof(BrowsableAttribute)))
               .ToList();

【讨论】:

  • 这也将包括[Browsable(false)]
猜你喜欢
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多