Pregunta

Estoy obteniendo "objeto no coincide con el tipo de destino" cuando intento recuperar el valor de un objeto en tiempo de ejecución en mi programa C#.

public void GetMyProperties(object obj)
{
  foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    if(!Helper.IsCustomType(pinfo.PropertyType))
    {
      string s = pinfo.GetValue(obj, null); //throws error during recursion call
      propArray.Add(s);
    }
    else
    {
      object o = pinfo.PropertyType;
      GetMyProperties(o);
    }
  }
}

Pase un objeto de mi clase BrokerInfo que tiene una propiedad de tipo corredor de tipo que tiene propiedades: FirstName y LastName (todas las cadenas por simplicidad).

- BrokerInfo
  - Broker
    - FirstName
    - LastName

Estoy tratando de verificar recursivamente los tipos personalizados y tratar de obtener sus valores. Puedo hacer por algo como:

- Broker
  - FirstName
  - LastName

Por favor ayuda.

Actualización: pude resolverlo con la ayuda de Leppie: aquí está el código modificado.

public void GetMyProperties(object obj)
{
  foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    if(!Helper.IsCustomType(pinfo.PropertyType))
    {
      string s = pinfo.GetValue(obj, null); 
      propArray.Add(s);
    }
    else
    {
      object o = pinfo.GetValue(obj, null);
      GetMyProperties(o);
    }
  }
}

Iscustom es mi método para verificar si el tipo es tipo custome o no. Aquí está el código:

public static bool IsCustomType(Type type)
{
    //Check for premitive, enum and string
    if (!type.IsPrimitive && !type.IsEnum && type != typeof(string))
    {
        return true;
    }
    return false;
}
¿Fue útil?

Solución

¿Por qué está perforando el tipo, en lugar de la instancia?

Específicamente aquí:

  object o = pinfo.PropertyType;
  GetMyProperties(o);

Debería verse algo como:

  var o = pinfo.GetValue(obj, null);
  GetMyProperties(o);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top