I'm trying to find all properties containing an object that implelents an interface, and execute a method on the object. This is the code I have so far:
foreach (var propertyInfo in this.GetType().GetProperties()
.Where(xx => xx.GetCustomAttributes(typeof(SearchMeAttribute), false).Any()))
{
if (propertyInfo.PropertyType.GetInterfaces().Any(xx => xx == typeof(IAmSearchable)))
{
// the following doesn't work, though I hoped it would
return ((IAmSearchable)propertyInfo).SearchMeLikeYouKnowIAmGuilty(term);
}
}
Unfortunately, I get the error:
Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'ConfigurationServices.ViewModels.IAmSearchable'.
How can I get the actual object, rather than the RuntimePropertyInfo
?
You need to get the value from the property with the GetValue
method:
object value = propertyInfo.GetValue(this, null);
The this
is the "target" of the property, and the null
indicates that you're expecting just a parameterless property, not an indexer.
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