简体   繁体   中英

Instantiate generic c# List when the reflected type itself is a List

I have a reflected Type, which ends up being a List<Type> . So I have:

Type modelType = GetMyType();

So - modelType could be List<ClassA> or List<ClassB> , etc. depending on the situation.

How do I create this type, and then populate it?

I know I can do this:

var myList = Activator.CreateInstance(modelType);

But then how do I add items to it, which I would normally do with myList.Add(new ClassA()) or myList.Add(new ClassB()) knowing that I don't really know the ClassA or ClassB type - I just know that modelType is List<ClassA> - Is there some other way I should be instantiating it so that I can add items to it?

Have a look at this example, it uses the Type.GetGenericArguments Method to retrieve the lists inner type. Then proceed with reflection as usual.

    static void Main(string[] args)
    {
        Type modelType = GetMyType();
        var myList = Activator.CreateInstance(modelType);

        var listInnerType = modelType.GetGenericArguments()[0];
        var listInnerTypeObject = Activator.CreateInstance(listInnerType);

        var addMethod = modelType.GetMethod("Add");
        addMethod.Invoke(myList, new[] { listInnerTypeObject });
    }
    static Type GetMyType()
    {
        return typeof(List<>).MakeGenericType((new Random().Next(2) == 0) ? typeof(A) : typeof(B));
    }

class A { }
class B { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM