2012-05-22 13 views
16

Sto cercando di ottenere i valori dagli oggetti all'interno di un elenco che fa parte di un oggetto principale.Uso della riflessione per ottenere valori dalle proprietà da un elenco di una classe

devo l'oggetto principale che contiene varie proprietà che possono essere raccolte.

In questo momento sto cercando di capire come accedere a un elenco generico contenuto nell'oggetto.

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

Ho cercato di utilizzare un SetValue() con MyObject su questo, ma errori fuori con (parafrasato):

oggetto non è di 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

Il codice per le parti pertinenti della classe che si sta tentando di riflettere potrebbe essere un po 'utile. –

+0

dal List eredita IList è possibile aggirare questo cambiando in 'IList oLista'? –

+1

Compilano anche questo? 'oLista' è un' oggetto', che non ha una proprietà chiamata 'PropertyType'. – FishBasketGordo

risposta

18

Per ottenere/impostare utilizzando il riflesso è necessario un esempio. Per scorrere gli elementi nell'elenco, provare questo:

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

it sembra che questo metodo potrebbe funzionare per accedere alla lista. Ho implementato una funzione per verificare se il tipo è una raccolta. – Romoku

+0

Questo dovrebbe essere facile - 'bool isCollection = (oLista is ICollection);' –

+0

Bello, ma manca una spiegazione su come ottenere le liste nidificate. Ad esempio MyObject.MyList [0] .SecondList [1] .SomeValue –

4

See se qualcosa del genere ti aiuta nella giusta direzione: ho avuto lo stesso errore un po 'di tempo fa e questo codice ha risolto il mio 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 
    } 
    } 
} 
Problemi correlati