2013-03-18 77 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();