2012-07-23 9 views
5

Estoy tratando de encontrar todas las propiedades que contienen un objeto que implementa una interfaz, y ejecutar un método en el objeto. Este es el código que tengo hasta ahora:¿Cómo obtener un objeto de RuntimePropertyInfo?

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

Por desgracia, me sale el error:

Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'ConfigurationServices.ViewModels.IAmSearchable'.

¿Cómo puedo obtener el objeto real, en lugar de la RuntimePropertyInfo?

Respuesta

12

que necesita para obtener el valor de la propiedad con el método GetValue:

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

El this es el "objetivo" de la propiedad, y el null indica que solo espera una propiedad sin parámetros, no es un indexador

+0

¡Gracias! su explicación lo hizo "clic" para mí. – Migs

Cuestiones relacionadas