Get property values from a class

4

I have the following codes:

private PropertyInfo[] ObterPropriedades(Type classe)
{
    PropertyInfo[] properties = classe.GetProperties();
    return properties;
}

private string[] ObterValoresPropriedades(Type classe)
{
   List<string> val = new List<string>();
   foreach (var valores in ObterPropriedades(classe))
       val.Add(valores.GetValue(valores,null).ToString());//aqui da o erro
   return val.ToArray();
}

it is returning me the following error:

  

Additional information: Object does not match the target type.

How do I get the value of the properties?

And how can I pass a class as a parameter to a method?

the way I passed the class as parameter Type classe and at the time of calling the method:

Pessoa p = new Pessoa();
ObterValoresPropriedades(p.GetType());

Is it a correct way? or are there other ways?

    
asked by anonymous 22.12.2014 / 18:01

2 answers

5

I would do so:

private string[] ObterValoresPropriedades(object objeto) {
   var val = new List<string>();
   foreach (var item in objeto.GetType().GetProperties())
       val.Add((item.GetValue(objeto) ?? "").ToString());
   return val.ToArray();
}

As you can see, you need to get the object to do the evaluation. The type (which you call class, but there are types that are not classes) is also required but it can be obtained from the object.

Then you call with:

ObterValoresPropriedades(p);
    
22.12.2014 / 18:14
3

You are passing only the Object type and not the Object, I would do it like this:

public string[] ObterValoresPropriedades(Object Objeto)
{
    var lista = new List<string>();
    var p = Objeto.GetType().GetProperties();

    foreach (PropertyInfo pop in p)
    {
        var valor = pop.GetValue(Objeto, null);
        if (valor != null)
            lista.Add(valor.ToString());
    }

    return lista.ToArray();
}

To call:

ObterValoresPropriedades(p)
    
22.12.2014 / 18:14