I would like to create a strongly type list and decide the type in runtime. This is my code.I thought it should work, but it doesn't :)
Type elementType = Type.GetType(parts[0].Trim(),false,true);
var elementsBeingSet = new List<elementType>();
would you have any ideat how to create a strongly typed list whose type I will decide in runtime ?
Duplicate: here are other versions:
最佳答案
使用Type.MakeGenericType(type[])
:
Type elementType = GetElementType(); // get this type at runtime
Type listType = typeof(List<>);
Type combinedType = listType.MakeGenericType(elementType);
IList elements = (IList) Activator.CreateInstance(combinedType);
IList
保留结果-因为您不知道在运行时将使用的实际类型。Dictionary<,>
之类的东西。关于c# - 确定运行时的类型并以通用类型应用它-我该怎么做?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/326285/