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?
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
– Laerte
It would have to be The Flash :P
– Maniero
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) ?? "")
– iuristona
This way it will populate the array with empty values.
– Laerte
Better than giving error :P of course you can avoid this if he wants, just put a
if
to prevent theAdd
happen,– Maniero