创建类型customType的列表

Abd*_*lla 3 c# types list

我试图创建一个在运行时设置的自定义类型的列表.这怎么可能?

这是我的代码:

Type customType = typeof(string); // or someOtherVariable.GetType();

List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found
Run Code Online (Sandbox Code Playgroud)

Jus*_*ner 7

如果要实例化某些反射类型的通用列表,则必须使用Reflection来执行此操作:

var type = typeof(string);

var list = typeof(List<>);
var listOfType = list.MakeGenericType(type);

var instance = Activator.CreateInstance(listOfType);
Run Code Online (Sandbox Code Playgroud)