Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建customType类型的列表_C#_List_Types - Fatal编程技术网

C# 创建customType类型的列表

C# 创建customType类型的列表,c#,list,types,C#,List,Types,我正在尝试创建在运行时设置的自定义类型的列表。这怎么可能 这是我的密码: Type customType = typeof(string); // or someOtherVariable.GetType(); List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found Type customType

我正在尝试创建在运行时设置的自定义类型的列表。这怎么可能

这是我的密码:

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

List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found
Type customType=typeof(string);//或者其他变量;
列表ls=新列表();//错误:找不到类型或命名空间名称“customType”

如果要实例化某个反射类型的通用列表,则必须使用反射:

var type = typeof(string);

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

var instance = Activator.CreateInstance(listOfType);
var type=typeof(字符串);
变量列表=类型(列表);
var listOfType=list.MakeGenericType(类型);
var instance=Activator.CreateInstance(listOfType);

您不能这样做。泛型集合在编译时是强类型的。您可能会发出/codegen一个新类,并在需要时动态编译它,但这是一个非常不同的问题

为什么不添加字符串而不是customType?此代码没有意义,您似乎正在创建字符串列表。实际上,该类型将在运行时设置。例如:Type customType=someOtherVariable.GetType();Justin Niessner的答案当然是正确的,但我要补充一点:这种技术在某些情况下很有用,但大多数情况下,你可以找到另一种解决方案,它不需要反射,同样好(或者更好,因为它更简单)。如果你可以发布更多关于你为什么要这样做的细节,你可能会得到更好地解决更大问题的建议。或者,你可以使用反射。(我没有对这个答案投反对票,但我认为这是其他人投反对票的原因。)既然变量“instance”的数据类型是var,它怎么能用作列表呢?@DrRiisTab-
var
不是数据类型。它只是一个快捷方式,允许编译器为您设置静态类型。如果要在列表中使用
实例
,则必须使用通用重载: