2013-08-17 59 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中属性以外的内容,并且您也引用了类变量,它们也不是属性。属性实际上是你想要的,而不是“类型”或属性应用于类的定义?