我正在尝试创建在运行时设置的自定义类型的列表。这怎么可能?
这是我的代码:
Type customType = typeof(string); // or someOtherVariable.GetType();
List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found
答案 0 :(得分:7)
如果要实例化某些反射类型的通用列表,则必须使用Reflection来执行此操作:
var type = typeof(string);
var list = typeof(List<>);
var listOfType = list.MakeGenericType(type);
var instance = Activator.CreateInstance(listOfType);
答案 1 :(得分:-1)
你不能这样做。泛型集合在编译时是强类型的。您可以发出/编译一个新类并在需要时动态编译它,但这是一个非常不同的问题