2013-08-17 61 views
0

我有以下方法返回Dictionary<string, string>作爲字典鍵的對象的所有公共成員(字段和屬性)的名稱。我可以得到成員的名字,但我無法得到他們的價值觀。誰能告訴我如何在下面的方法來實現這一目標:獲取成員的名稱和值

public Dictionary<String, String> ObjectProperty(object objeto) 
{ 
    Dictionary<String, String> dictionary = new Dictionary<String, String>(); 

    Type type = objeto.GetType(); 
    FieldInfo[] field = type.GetFields(); 
    PropertyInfo[] myPropertyInfo = type.GetProperties(); 

    String value = null; 

    foreach (var propertyInfo in myPropertyInfo) 
    { 
     value = (string)propertyInfo.GetValue(this, null); //Here is the error 
     dictionary.Add(propertyInfo.Name.ToString(), value); 
    } 

    return dictionary; 
} 

錯誤:

對象不匹配目標類型。 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。

異常詳細信息:System.Reflection.TargetException:Object與目標類型不匹配。

+0

「錯誤」?哪個錯誤? –

+0

你不應該傳遞對象的實例來獲取值嗎? –

+1

屬性!=屬性 –

回答

2

這裏包括兩個:

  1. 你傳遞this,而不是objeto,這意味着你想讀的屬性出現在錯誤的對象。
  2. 您無法確保您只是嘗試讀取不是索引器的屬性。

嘗試改變的foreach這樣:

foreach (var propertyInfo in myPropertyInfo) 
{ 
    if (propertyInfo.GetIndexParameters().Length == 0) 
    { 
     value = (string) propertyInfo.GetValue(objeto, null); 
     dictionary.Add(propertyInfo.Name.ToString(), value); 
    } 
} 
1

的注意事項,在這裏:

foreach (var propertyInfo in myPropertyInfo) 
{ 
    value = (string) propertyInfo.GetValue(this, null); //Here is the error 
    dictionary.Add(propertyInfo.Name.ToString(), value); 

} 

我們假定你是你所有的屬性都是字符串。他們?

如果他們都沒有,但是你想要的字符串,無論如何,你可以使用此代碼:

object objValue = propertyInfo.GetValue(objeto, null);  
value = (objValue == null) ? null : objValue.ToString(); 

上面的代碼還考慮到該屬性值可以爲空。我沒有考慮索引屬性的可能性,但如果你有任何需要,你需要適應它們。

此外,正如Lasse V. Karlsen指出的那樣,通過傳遞this而不是objeto,您試圖從方法的父類中提取屬性值,而不是從objeto中提取屬性值。如果他們不是同一個對象,你將不會得到你想要的結果;如果它們不是類型的對象,那麼你會得到一個錯誤。

最後,您已經使用了術語「屬性」,它指的是.NET中屬性以外的內容,並且您也引用了類變量,它們也不是屬性。屬性實際上是你想要的,而不是「類型」或屬性應用於類的定義?