1

为了清楚起见,举个小例子:

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?
            }
        }
    }
}

任何建议都会非常感激。提前致谢。

4

1 回答 1

4

我认为使用 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;
于 2013-03-21T03:39:48.857 回答