为了清楚起见,举个小例子:
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;
}
问题是:如何仅获取isListed
设置了 bool 参数的true
属性MyAttrib
?
这就是我得到的:
PropertyInfo[] myProps = myBookInstance.
GetType().
GetProperties().
Where(x => (x.GetCustomAttributes(typeof(MyAttrib), false).Length > 0)).ToArray();
myProps
从 获取所有属性,但是现在,当其参数返回 falseBook
时,我无法弄清楚如何排除它们。isListed
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?
}
}
}
}
任何建议都会非常感激。提前致谢。