获取 Browsable 属性的所有属性
Get all properties of Browsable attribute
我有一个 class,它有很多属性,有些属性有 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
的属性?在这种情况下,我只需要获得 prpName
和 prpCity
。
这是我目前试过的代码。
List<PropertyInfo> pInfo = typeof(MyClass).GetProperties().ToList();
但这会选择所有属性。有什么方法可以过滤只有 Browsable attributes
的属性吗?
您可以使用 Attribute.IsDefined
方法检查 Browsable
属性是否在 属性 中定义:
typeof(MyClass).GetProperties()
.Where(pi => Attribute.IsDefined(pi, typeof(BrowsableAttribute)))
.ToList();
要仅包括具有 [Browsable(true)]
的成员,您可以使用:
typeof(MyClass).GetProperties()
.Where(pi => pi.GetCustomAttributes<BrowsableAttribute>().Contains(BrowsableAttribute.Yes))
.ToList();
我有一个 class,它有很多属性,有些属性有 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
的属性?在这种情况下,我只需要获得 prpName
和 prpCity
。
这是我目前试过的代码。
List<PropertyInfo> pInfo = typeof(MyClass).GetProperties().ToList();
但这会选择所有属性。有什么方法可以过滤只有 Browsable attributes
的属性吗?
您可以使用 Attribute.IsDefined
方法检查 Browsable
属性是否在 属性 中定义:
typeof(MyClass).GetProperties()
.Where(pi => Attribute.IsDefined(pi, typeof(BrowsableAttribute)))
.ToList();
要仅包括具有 [Browsable(true)]
的成员,您可以使用:
typeof(MyClass).GetProperties()
.Where(pi => pi.GetCustomAttributes<BrowsableAttribute>().Contains(BrowsableAttribute.Yes))
.ToList();