dimanche 20 octobre 2019

How to get List

As suggested by @John, here is re-write:

Consider this code:

public object Foo(object original)
{
    List<object> origList = original as List<object>;    //problematic line, origList is null even though it was initialized as [1,2,3] in main method
    List<object> copy = new List<object>();

    foreach (var item in origList)
        copy.Add(item);

    return copy;
}

class Example
{
    List<int> someList = new List<int>() { 1,2,3 };
    // and also other Lists, I dont know their type at compile time
    // and other fields and methods
}

//in usage method:

Example e1 = new Example();
object obj1 = e1;    // this is original
Example e2 = new Example();
object obj2 = e2;   // this is copy

FieldInfo[] fields_of_class = obj1.GetType().GetFields(
            BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

foreach(FieldInfo fi in fields_of_class)
{
    object currentObject = fi.GetValue(obj1);

    // do type checking
    if (IsList(currentObject)
    {
        fi.SetValue(obj2, Foo(currentObject));    // here I have to retrive copy of the list, but I dont know generic argument beforehand as it can be List<insert any type here>
    }
}

How can I get that original list from System.Object in Foo method?

Preferably, I would like not to use generic methods as I would have to MakeGenericMethod which is slow for me. But if that's only solution I take it.

Now I know this isn't the smallest code example. Right now, I am looking into some other solutions of the problem.





Aucun commentaire:

Enregistrer un commentaire