How to instantiate List but T is unknown until runtime?

后端 未结 4 1200
一整个雨季
一整个雨季 2020-12-31 10:05

Assume I have a class that is unknown until runtime. At runtime I get a reference, x, of type Type referencing to Foo.GetType(). Only by using x and List<>, can I create

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 10:47

    Type x = typeof(Foo);
    Type listType = typeof(List<>).MakeGenericType(x);
    object list = Activator.CreateInstance(listType);
    

    Of course you shouldn't expect any type safety here as the resulting list is of type object at compile time. Using List would be more practical but still limited type safety because the type of Foo is known only at runtime.

    提交回复
    热议问题