【发布时间】:2013-03-10 10:55:41
【问题描述】:
为了清楚起见,举个小例子:
public class Book
{
[MyAttrib(isListed = true)]
public string Name;
[MyAttrib(isListed = false)]
public DateTime ReleaseDate;
[MyAttrib(isListed = true)]
public int PagesNumber;
[MyAttrib(isListed = false)]
public float Price;
}
问题是:如何仅获取在 MyAttrib 上设置了布尔参数 isListed 的属性 true?
这是我得到的:
PropertyInfo[] myProps = myBookInstance.
GetType().
GetProperties().
Where(x => (x.GetCustomAttributes(typeof(MyAttrib), false).Length > 0)).ToArray();
myProps 从Book 获得了所有属性,但是现在,当它的isListed 参数返回false 时,我不知道如何排除它们。
foreach (PropertyInfo prop in myProps)
{
object[] attribs = myProps.GetCustomAttributes(false);
foreach (object att in attribs)
{
MyAttrib myAtt = att as MyAttrib;
if (myAtt != null)
{
if (myAtt.isListed.Equals(false))
{
// if is true, should I add this property to another PropertyInfo[]?
// is there any way to filter?
}
}
}
}
任何建议都会非常感激。提前致谢。
【问题讨论】:
标签: c# reflection properties filter attributes