How to get an object from RuntimePropertyInfo?

I am trying to find all properties containing an object that implements an interface, and execute a method on an object. This is the code that I still have:

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

Sorry, I get an error message:

Cannot overlay object of type "System.Reflection.RuntimePropertyInfo" with type "ConfigurationServices.ViewModels.IAmSearchable".

How can I get the actual object, not RuntimePropertyInfo?

+5
source share
1 answer

You need to get the value from the property using the method GetValue:

object value = propertyInfo.GetValue(this, null);

this- this is the "goal" of the property, which nullmeans that you are simply expecting a property with no parameters, not an indexer.

+12
source

All Articles