Verwenden von Reflection, um Werte aus Eigenschaften aus einer Liste einer Klasse abzurufen

Ich versuche, die Werte von Objekten in einer Liste abzurufen, die Teil eines Hauptobjekts ist.

Ich habe das Hauptobjekt, das verschiedene Eigenschaften enthält, die Sammlungen sein können.

Im Moment versuche ich herauszufinden, wie man auf eine generische Liste zugreift, die im Objekt enthalten ist.

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

Ich habe versucht, eine zu verwendenSetValue() mit MyObject auf diese, aber es Fehler mit (umschrieben):

Objekt ist nicht vom Typ

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

Antworten auf die Frage(2)

Ihre Antwort auf die Frage