2013-03-18 78 views
2

例如:我有这个类如何筛选类属性集合?

public class MyClass 
{ 
    private string propHead; 
    private string PropHead { get; set; } 

    private int prop01; 
    private int Prop01 { get; set; } 

    private string prop02; 
    private string Prop02 { get; set; } 

    // ... some more properties here 

    private string propControl; 
    private string PropControl { get; } // always readonly 
} 

我需要排除propHead和propControl。 要排除propControl:

MyClass mc = new MyClass(); 
PropertyInfo[] allProps = mc.GetType().GetProperties().Where(x => x.CanWrite).ToArray(); 

现在,我怎么能排除propHead?当无障碍环境的所有共享相同的水平。有什么办法可以为propHead添加一个特殊属性,让我可以将它排除在外。 属性名称在每个类中总是不同的。

任何建议将是非常apreciated。

回答

1

这将是最简单的方法:

MyClass mc = new MyClass(); 
PropertyInfo[] allProps = mc.GetType() 
    .GetProperties() 
    .Where(x => x.Name != "propHead" && x.Name != "propControl") 
    .ToArray(); 

但是,如果你正在寻找一个更通用的解决方案,你可以试试这个

public class CustomAttribute : Attribute 
{ 
    ... 
} 

MyClass mc = new MyClass(); 
PropertyInfo[] allProps = mc.GetType() 
    .GetProperties() 
    .Where(x => x.GetCustomAttributes(typeof(CustomAttribute)).Length > 0) 
    .ToArray();