2015-02-11 146 views
0

我有一个有很多属性的类,有些属性有Browsable属性。获取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的房产?

+0

你想拥有可浏览所有属性, 对?或者只有Browsable(true)的那些? – 2015-02-11 15:20:37

+0

所有可浏览的属性@ Selman22 – 2015-02-11 15:27:46

回答

1

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

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

这也包括'[Browsable(false)]'。 – SLaks 2015-02-11 15:14:26

+1

完美运作。非常感谢兄弟:) @ Selman22 – 2015-02-11 15:33:12

0

要为[Browsable(true)]唯一成员包括,你可以使用:

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

如何获得标记为Browsable的列的值为false。 – Prithiv 2016-12-21 09:21:51