0

I have the following method to return a Dictionary<string, string> with the names of all public members (fields and properties) of an object as the dictionary key. I can get the name of the members, but I can't get their values. Could anyone tell me how to achieve this in the method below:

 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;
}

Error:

Object does not match target type. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.TargetException: Object does not match target type.

4

2 回答 2

2

Two things here:

  1. You're passing in this, instead of objeto, which means you're trying to read the properties off of the wrong object.
  2. You're not ensuring that you're only trying to read properties that aren't indexers.

Try changing the foreach to this:

foreach (var propertyInfo in myPropertyInfo)
{
    if (propertyInfo.GetIndexParameters().Length == 0)
    {
        value = (string) propertyInfo.GetValue(objeto, null);
        dictionary.Add(propertyInfo.Name.ToString(), value);
    }
}
于 2013-08-17T14:52:39.683 回答
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 中的属性以外的东西,并且您还提到了类变量,它们也不是属性。属性实际上是您想要的,而不是应用于类定义的“字段”或属性吗?

于 2013-08-17T15:37:51.907 回答