在运行时决定类型和泛型类型应用它 - 我该怎么办呢? [英] Deciding on type in the runtime and applying it in generic type - how can I do this?
问题描述
我想创建一个强类型列表,并决定在运行时的类型。这是我的code.I认为它应该工作,但它不会:)
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>();
请问您有什么ideat如何创建一个强类型的列表,它的类型,我会在运行时决定?
would you have any ideat how to create a strongly typed list whose type I will decide in runtime ?
复制:这里有其他的版本:
Duplicate: here are other versions:
- http://stackoverflow.com/questions/234008/is-it-impossible-to-use-generics-dynamically
- http://stackoverflow.com/questions/307984/declare-a-generic-type-instance-dynamically
- http://stackoverflow.com/questions/325156/calling-generic-method-with-a-type-argument-known-only-at-execution-time
推荐答案
使用 Type.MakeGenericType(类型[])
:
Type elementType = GetElementType(); // get this type at runtime
Type listType = typeof(List<>);
Type combinedType = listType.MakeGenericType(elementType);
IList elements = (IList) Activator.CreateInstance(combinedType);
您必须使用的IList
来保持的结果 - 因为你不知道会在运行时使用的实际类型
You have to use IList
to keep the result - because you don't know the actual type that will be used at runtime.
有关泛型类型的,你会使用类似词典&LT多个类型的参数;,&GT;
For generic types with more than one type parameter you would use something like Dictionary<,>
.
又见<一个href=\"http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx\">http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
这篇关于在运行时决定类型和泛型类型应用它 - 我该怎么办呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!