Initialize generic object from a System.Type

后端 未结 1 1538
北恋
北恋 2021-02-07 04:02

I need to create a generic type, but I do not know the type at compile time. I would like to do this:

Type t = typeof(whatever);
var list = new List


        
相关标签:
1条回答
  • 2021-02-07 04:35

    Like this:

    Type t;
    Type genericListType = typeof(List<>).MakeGenericType(t);
    object list = Activator.CreateInstance(genericListType);
    

    Note that you can only assign it to a variable of type object. (Although you can cast to to the non-generic IList interface)

    To use the list variable, you'll probably need reflection.

    0 讨论(0)
提交回复
热议问题