如何实例化List< T>但是直到运行时T才是未知的? [英] How to instantiate List<T> but T is unknown until runtime?

查看:42
本文介绍了如何实例化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.

这篇关于如何实例化List&lt; T&gt;但是直到运行时T才是未知的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆