2012-05-22 16 views
16

Estoy tratando de obtener los valores de los objetos dentro de una lista que es parte de un objeto principal.Usar la reflexión para obtener valores de propiedades de una lista de una clase

Tengo el objeto principal que contiene varias propiedades que pueden ser colecciones.

Ahora estoy tratando de averiguar cómo acceder a una lista genérica que está contenida en el objeto.

///<summary> 
///Code for the inner class 
///</summary> 
public class TheClass 
{ 
    public TheClass(); 

    string TheValue { get; set; } 
} //Note this class is used for serialization so it won't compile as-is 

///<summary> 
///Code for the main class 
///</summary> 
public class MainClass 
{ 
    public MainClass(); 

    public List<TheClass> TheList { get; set; } 
    public string SomeOtherProperty { get; set; } 
    public Class SomeOtherClass { get; set } 
} 


public List<MainClass> CompareTheValue(List<object> MyObjects, string ValueToCompare) 
{ 
    //I have the object deserialised as a list 
    var ObjectsToReturn = new List<MainClass>(); 
    foreach(var mObject in MyObjects) 
    { 

     //Gets the properties 
     PropertyInfo piTheList = mObject.GetType().GetProperty("TheList"); 

     object oTheList = piTheList.GetValue(MyObject, null); 


     //Now that I have the list object I extract the inner class 
     //and get the value of the property I want 
     PropertyInfo piTheValue = oTheList.PropertyType 
              .GetGenericArguments()[0] 
              .GetProperty("TheValue"); 

     //get the TheValue out of the TheList and compare it for equality with 
     //ValueToCompare 
     //if it matches then add to a list to be returned 

     //Eventually I will write a Linq query to go through the list to do the comparison. 
     ObjectsToReturn.Add(objectsToReturn); 

    } 
return ObjectsToReturn; 
} 

He tratado de utilizar un SetValue() con MiObjeto en esto, pero con errores hacia fuera (parafraseado):

objeto no es de tipo

private bool isCollection(PropertyInfo p) 
{ 
    try 
    { 
     var t = p.PropertyType.GetGenericTypeDefinition(); 
     return typeof(Collection<>).IsAssignableFrom(t) || 
       typeof(Collection).IsAssignableFrom(t); 
    } 
    catch 
    { 
     return false; 
    } 
    } 
} 
+2

El código para las partes pertinentes de la clase que está tratando de reflejar podría ser un poco útil. –

+0

desde lista hereda IList ¿se puede solucionar esto cambiando a 'IList oTheList'? –

+1

¿Esto incluso compila? 'oTheList' es un' object', que no tiene una propiedad llamada 'PropertyType'. – FishBasketGordo

Respuesta

18

Para obtener/configurar mediante reflexión necesita una instancia. Para recorrer los elementos de la lista intente esto:

PropertyInfo piTheList = MyObject.GetType().GetProperty("TheList"); //Gets the properties 

IList oTheList = piTheList.GetValue(MyObject, null) as IList; 

//Now that I have the list object I extract the inner class and get the value of the property I want 

PropertyInfo piTheValue = piTheList.PropertyType.GetGenericArguments()[0].GetProperty("TheValue"); 

foreach (var listItem in oTheList) 
{ 
    object theValue = piTheValue.GetValue(listItem, null); 
    piTheValue.SetValue(listItem,"new",null); // <-- set to an appropriate value 
} 
+0

parece que este método podría funcionar para acceder a la lista. Implementé una función para verificar si el tipo es una Colección. – Romoku

+0

Eso debería ser fácil: 'bool isCollection = (oTheList es ICollection);' –

+0

Bueno, pero falta una explicación sobre cómo lograr establecer listas anidadas. Por ejemplo MyObject.MyList [0] .SecondList [1] .SomeValue –

4

Ver si algo como esto te ayuda en la dirección correcta: Hace un tiempo recibí el mismo error y este código solucionó mi problema.

PropertyInfo[] properties = MyClass.GetType().GetProperties(); 
foreach (PropertyInfo property in properties) 
{ 
    if (property.Name == "MyProperty") 
    { 
    object value = results.GetType().GetProperty(property.Name).GetValue(MyClass, null); 
    if (value != null) 
    { 
    //assign the value 
    } 
    } 
} 
Cuestiones relacionadas