Get property values of a class

Asked

Viewed 4,042 times

6

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

he is returning me the following error:

Additional information: Object does not match target type.

How do I get property value?

And you can pass a class as a parameter to a method?

the way I passed the class as parameter Type classe and at the time to call the metodo:

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

is a correct way? or are there other ways?

2 answers

7


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

I put in the Github for future reference.

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

Then you call with:

ObterValoresPropriedades(p);
  • bigown, you posted the answer almost at the same time as mine! The similarity of the code looks like one picked up from the other, haha

  • 1

    It would have to be The Flash :P

  • 2

    Remembering that item.GetValue(objeto, null) can return Nullreferenceexception if any property has value null, so a coalition would be required. (item.GetValue(objeto, null) ?? "")

  • This way it will populate the array with empty values.

  • Better than giving error :P of course you can avoid this if he wants, just put a if to prevent the Add happen,

4

You are passing only the type of the Object and not the Object, I would do as follows:

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.