Skip to main content
 首页 » 编程设计

c#之我如何获得完成在其属性值中建立的要求的所有类属性

2024年02月13日19sxdcgaq8080

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

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 上 bool 参数 isListed 设置为 true 的属性?

这是我得到的:

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

myProps 获得了 Book 的所有属性,但是现在,当它的 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? 
            } 
        } 
    } 
} 

如有任何建议,我们将不胜感激。提前致谢。

请您参考如下方法:

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