2008-11-28 54 views
7

我想创建一个强类型列表并在运行时决定类型。这是我的code.I认为它应该工作,但它不会:)确定运行时类型并将其应用于泛型 - 我该怎么做?

 Type elementType = Type.GetType(parts[0].Trim(),false,true); 
     var elementsBeingSet = new List<elementType>(); 

请问您有什么ideat如何创建一个强类型的列表,它的类型,我会在运行时决定?

重复:这里有其它版本:

+0

对不起,我找不到其他人。 – 2008-11-28 17:47:50

回答

20

使用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<,>之类的东西。

又见http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx