为了说明这一点,我举个小例子:
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;
}
问题是:我如何只获得属性,其中bool参数isListed
在MyAttrib
上设置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?
}
}
}
}
任何建议都将非常感谢。
我认为使用Linq的查询语法会更容易一些。
var propList =
from prop in myBookInstance.GetType()
.GetProperties()
let attrib = prop.GetCustomAttributes(typeof(MyAttrib), false)
.Cast<MyAttrib>()
.FirstOrDefault()
where attrib != null && attrib.isListed
select prop;