我有以下方法返回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与目标类型不匹配。
“错误”?哪个错误? –
你不应该传递对象的实例来获取值吗? –
属性!=属性 –