如何获得所有类属性来完成在其属性值中建立的请求



为了说明这一点,我举个小例子:

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参数isListedMyAttrib上设置true ?

这是我得到的:

PropertyInfo[] myProps = myBookInstance.
                         GetType().
                         GetProperties().
                         Where(x => (x.GetCustomAttributes(typeof(MyAttrib), false).Length > 0)).ToArray();

myPropsBook获得所有属性,但是现在,我不知道如何排除它们,当它的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;

相关内容

  • 没有找到相关文章

最新更新