我正在尝试查找包含实现接口的对象的所有属性,并对该对象执行方法。这是我到目前为止的代码:
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);
}
}
不幸的是,我收到错误:
无法将类型为“System.Reflection.RuntimePropertyInfo”的对象强制转换为“ConfigurationServices.ViewModels.IAmSearchable”。
如何获取实际对象,而不是RuntimePropertyInfo
?
答案 0 :(得分:12)
您需要使用GetValue
方法从属性中获取值:
object value = propertyInfo.GetValue(this, null);
this
是属性的“目标”,null
表示您只期望无参数属性,而不是索引器。