【问题标题】:How do I get all class properties that accomplish a requisit established in its attribute value?如何获得所有完成在其属性值中建立的要求的类属性?
【发布时间】: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();

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

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

【问题讨论】:

    标签: c# reflection properties filter attributes


    【解决方案1】:

    我认为使用 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;
    

    【讨论】:

      猜你喜欢
      • 2022-12-28
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      相关资源
      最近更新 更多