我想创建一个在运行时设置的自定义类型的列表。这怎么可能?创建类型的列表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
我想创建一个在运行时设置的自定义类型的列表。这怎么可能?创建类型的列表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
如果你想要实例一些反映类型的泛型列表,你将不得不使用反射来做到这一点:
var type = typeof(string);
var list = typeof(List<>);
var listOfType = list.MakeGenericType(type);
var instance = Activator.CreateInstance(listOfType);
如何将变量'instance'用作列表,因为它的数据类型是var? – DrRiisTab
@DrRiisTab - 'var'不是数据类型。这只是一个让编译器为你设置静态类型的快捷方式。如果要在列表中使用'instance',则必须使用Generic重载:https://msdn.microsoft.com/en-us/library/0hcyx2kd(v=vs.110).aspx –
你不能这样做这个。泛型集合在编译时是强类型的。你也许可以发出/ codegen一个新类并在需要时动态编译它,但这是一个非常不同的问题
或,你可以使用反射。 (我没有低估这个答案,但我认为这是别人做的原因。) – phoog
为什么不只是添加字符串而不是customType? –
这段代码没有意义,你似乎正在创建一个字符串列表。 – Arran
实际上,类型将在运行时设置。例如:输入customType = someOtherVariable.GetType(); – Abdulla