获取成员的名称和值

本文关键字:成员 获取 | 更新日期: 2023-09-27 18:28:04

我有以下方法返回一个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:对象与目标类型不匹配。

获取成员的名称和值

这里有两件事:

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

注意,在这里:

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();

上面的代码还考虑到属性值可能为 null。 我没有考虑索引属性的可能性,但是如果您有索引属性,则需要容纳它们。

此外,正如 Lasse V. Karlsen 所指出的,通过传递 this 而不是 objeto ,您正在尝试从方法的父类中提取属性值,而不是objeto。 如果它们不是同一个对象,您将无法获得所需的结果;如果它们甚至不是同一类型的对象,那么您会收到错误。

最后,你使用了术语"属性",它指的是 .NET 中的属性以外的其他内容,并且还引用了类变量,这些变量也不是属性。 属性是否真的是您想要的,而不是应用于类定义的"字段"或属性?