如何实例化List< T>但是直到运行时T才是未知的?
问题描述:
假设我有一个直到运行时才知道的类.在运行时,我得到类型为Foo.GetType()的Type类型的引用x.只有使用x和List<>,我才能创建Foo类型的列表吗?
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 a list of type Foo?
该怎么做?
答
Type x = typeof(Foo);
Type listType = typeof(List<>).MakeGenericType(x);
object list = Activator.CreateInstance(listType);
当然,您不应期望此处有任何类型的安全性,因为在编译时结果列表的类型为 object
.使用 List< object>
会更实用,但类型安全仍然有限,因为 Foo
的类型仅在运行时才知道.
Of course you shouldn't expect any type safety here as the resulting list is of type object
at compile time. Using List<object>
would be more practical but still limited type safety because the type of Foo
is known only at runtime.