我想创建一个强类型列表并在运行时决定类型.这是我的代码.我认为它应该工作,但它没有:)
Type elementType = Type.GetType(parts[0].Trim(),false,true);
var elementsBeingSet = new List<elementType>();
Run Code Online (Sandbox Code Playgroud)
你有什么想法如何创建一个强类型列表,其类型我将在运行时决定?
重复:这是其他版本:
con*_*tor 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);
Run Code Online (Sandbox Code Playgroud)
您必须使用IList
保留结果 - 因为您不知道将在运行时使用的实际类型.
对于具有多个类型参数的泛型类型,您可以使用类似的东西Dictionary<,>
.
另请参见http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
归档时间: |
|
查看次数: |
7049 次 |
最近记录: |