2012-09-18 22 views
22

一類的價值觀我哈瓦一類是這樣的:如何讓所有的靜態屬性和它的使用反射

public class tbl050701_1391_Fields 
{ 
    public static readonly string StateName = "State Name"; 
    public static readonly string StateCode = "State Code"; 
    public static readonly string AreaName = "Area Name"; 
    public static readonly string AreaCode = "Area Code"; 
    public static readonly string Dore = "Period"; 
    public static readonly string Year = "Year"; 
} 

我想寫一個返回Dictionary<string, string>具有這些價​​值的一些語句:

Key       Value 
-------------------------------------------- 
"StateName"     "State Name" 
"StateCode"     "State Code" 
"AreaName"      "Area Name" 
"Dore"       "Period" 
"Year"       "Year" 

我有獲得一個屬性值驗證碼:

public static string GetValueUsingReflection(object obj, string propertyName) 
{ 
    var field = obj.GetType().GetField(propertyName, BindingFlags.Public | BindingFlags.Static); 
    var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty; 
    return fieldValue; 
} 

如何,我可以得到所有的屬性和它們的值?

+0

那些是靜態字段,而不是靜態屬性。你想要兩個嗎?還是隻有田野? – CodesInChaos

回答

39

我怎麼能得到所有proprities和他們的價值?

好下手,你需要領域性能區分。看起來你在這裏有田野。所以你想要的東西是這樣的:

public static Dictionary<string, string> GetFieldValues(object obj) 
{ 
    return obj.GetType() 
       .GetFields(BindingFlags.Public | BindingFlags.Static) 
       .Where(f => f.FieldType == typeof(string)) 
       .ToDictionary(f => f.Name, 
          f => (string) f.GetValue(null)); 
} 
+1

謝謝,爲我工作 – Rana