我有以下方法返回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與目標類型不匹配。
「錯誤」?哪個錯誤? –
你不應該傳遞對象的實例來獲取值嗎? –
屬性!=屬性 –