Reputation: 21401
I have a class which have many properties and some properties have Browsable
attribute.
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; }
}
}
Now using Reflection
, how can I filter the properties which have Browsable attributes
? In this case I need to get prpName
and prpCity
only.
Here is the code I have tried so far.
List<PropertyInfo> pInfo = typeof(MyClass).GetProperties().ToList();
but this selects all the properties. Is there any way to filter properties which have Browsable attributes
only?
Upvotes: 1
Views: 3643
Reputation: 10373
To include only members having [Browsable(true)]
, you can use:
typeof(MyClass).GetProperties()
.Where(pi => pi.GetCustomAttributes<BrowsableAttribute>().Contains(BrowsableAttribute.Yes))
.ToList();
Upvotes: 4
Reputation: 101731
You can use Attribute.IsDefined
method to check if Browsable
attribute is defined in property:
typeof(MyClass).GetProperties()
.Where(pi => Attribute.IsDefined(pi, typeof(BrowsableAttribute)))
.ToList();
Upvotes: 1