【发布时间】:2012-08-30 09:32:48
【问题描述】:
我正在尝试创建在运行时设置的自定义类型的列表。这怎么可能?
这是我的代码:
Type customType = typeof(string); // or someOtherVariable.GetType();
List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found
【问题讨论】:
-
为什么不直接添加字符串而不是 customType?
-
这段代码没有意义,你好像在创建一个字符串列表。
-
实际上,类型将在运行时设置。例如:键入 customType = someOtherVariable.GetType();
-
Justin Niessner 的回答当然是正确的,但我要补充一点:该技术在某些情况下很有用,但大多数情况下,您可以找到另一个不需要反射且同样出色的解决方案(或者,更确切地说,更好,因为它更简单)。如果您可以发布有关为什么您想要这样做的更多详细信息,您可能会得到更好地解决更大问题的建议。