创建具有不知道类型的列表

时间:2014-03-31 16:36:47

标签: c#

为什么在C#中我写不出来

MyClass m = new MyClass(2,3);
Type T = m.GetType();
List<T> ll = new List<T>();

或类似

MyClass m = new MyClass(2,3);
Type T = typeof(m);
List<T> ll = new List<T>();

...

是否可以更改此代码并编写类似的内容?

2 个答案:

答案 0 :(得分:0)

尽管在运行时解析了泛型,但编译器提供了安全检查。因此,在键入List<MyClass>...=

等语句时,需要您指定类名而不是Type的实例

即指定类型而不是传递Type实例。

如果您希望拥有在执行时解析的泛型,则必须使用反射。 看到 http://msdn.microsoft.com/en-us/library/system.type.makegenerictype%28v=vs.110%29.aspx

答案 1 :(得分:0)

您可以尝试这样的事情:

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

您可以将Activator的结果转换为IList以访问其方法。

var list = (IList)Activator.CreateInstance(listType);

当然,你不应该期望任何类型安全,因为结果列表在编译时是object类型。使用List会更实用但仍然限制类型安全性,因为Foo的类型仅在运行时才知道。

您还可以阅读更多相关信息here