如何从RuntimePropertyInfo获取对象?

Dav*_*Dev 5 c# reflection

我正在尝试查找包含实现接口的对象的所有属性,并在对象上执行方法.这是我到目前为止的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到错误:

无法将类型为"System.Reflection.RuntimePropertyInfo"的对象强制转换为"ConfigurationServices.ViewModels.IAmSearchable".

我怎样才能获得实际的对象,而不是RuntimePropertyInfo?

Jon*_*eet 12

您需要使用以下GetValue方法从属性中获取值:

object value = propertyInfo.GetValue(this, null);
Run Code Online (Sandbox Code Playgroud)

它this是属性的"目标",null表示您只期望一个无参数属性,而不是索引器.