I'm trying to get the value from a PropertyInfo[]
, but I can't get it to work:
foreach (var propertyInfo in foo.GetType().GetProperties())
{
var value = propertyInfo.GetValue(this, null);
}
Exception:
Object does not match target type.
Isn't this how it's supposed to be done?
GetValue(Object) Returns the property value of a specified object.
< Previous Next > The PropertyInfo class discovers the attributes of a property and provides access to property metadata. The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.
To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null , the property will be set to the default value for that type.
You're trying to get properties from this
when you originally fetched the PropertyInfo
s from foo.GetType()
. So this would be more appropriate:
var value = propertyInfo.GetValue(foo, null);
That's assuming you want to effectively get foo.SomeProperty
etc.
You're getting that exception because this
isn't the same type as foo
.
You should make sure you're getting the properties for the same object that you're going to try to get the value from. I'm guessing from your code that you're expecting this to be foo inside the scope of the loop (which isn't the case at all), so you need to change the offending line to:
var value = propertyInfo.GetValue(foo, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With