C#:实例化一个List,给出一个Type 的引用

假设在C#中, myType是对某些Type的引用。 仅使用myType ,是否可以创建myType对象List

例如,在下面的代码中,虽然它是错误的,但我想实例化via

new List < myType > ( )

 using System ; using System.Reflection ; using System.Collections.Generic ; class MyClass { } class MainClass { public static void Main ( string [] args ) { Type myType = typeof ( MyClass ) ; List  myList = new List  ( ) ; } } 

你可以使用Reflection做到这一点:

 Type typeList = typeof(List<>); Type actualType = typeList.MakeGenericType(myType); object obj = Activator.CreateInstance(actualType); 

如何使用reflection动态创建通用C#对象?

您可以使用reflection,但由于返回列表的类型在编译时是未知的,因此使用返回列表的代码必须通过松散类型的接口访问成员。

仅使用List,这不会导致代码更快或可维护。

更好的解决方案是创建一个List < interface >,其中< interface >是您在运行时可以放入列表中的所有类型的最强公共接口或基类。 至少就是这样,在使用列表成员时,您不必从对象来回转换,并且您将对列表中的各种事物进行编译时validation。

有没有理由使用

List' instead of myType List' instead of List`

基本上,您的代码希望在集合(列表)中存储类型在编译时未知的对象。

我想说,如果你打算制作这个生产代码,要么使用List,要么使用inheritance并存储基类列表。

这是不可能的,因为myType在编译时是未知的,您无法在代码中操作此列表。 您可以使用reflection来创建数组。