C# 在运行时决定类型并在泛型类型中应用它-我如何做到这一点?
我想创建一个强类型列表,并在运行时决定类型。这是我的代码。我认为它应该工作,但它没有:)C# 在运行时决定类型并在泛型类型中应用它-我如何做到这一点?,c#,types,C#,Types,我想创建一个强类型列表,并在运行时决定类型。这是我的代码。我认为它应该工作,但它没有:) Type elementType=Type.GetType(parts[0].Trim(),false,true); var elementsBeingSet=新列表(); 您是否知道如何创建一个强类型列表,我将在运行时决定它的类型 重复:以下是其他版本: 使用Type.MakeGenericType(Type[]): Type elementType=GetElementType();//在运行
Type elementType=Type.GetType(parts[0].Trim(),false,true);
var elementsBeingSet=新列表();
您是否知道如何创建一个强类型列表,我将在运行时决定它的类型
重复:以下是其他版本:
Type.MakeGenericType(Type[])
:
Type elementType=GetElementType();//在运行时获取此类型
类型listType=typeof(列表);
类型combinedType=listType.MakeGenericType(elementType);
IList元素=(IList)Activator.CreateInstance(combinedType);
您必须使用IList
来保留结果,因为您不知道运行时将使用的实际类型
对于具有多个类型参数的泛型类型,可以使用类似于字典的内容
另请参见对不起,我找不到其他的。无论是否重复,我搜索了几个“重复项”,但这里的问题+示例非常清楚,答案也非常清楚,因此非常有用。
Type elementType = Type.GetType(parts[0].Trim(),false,true);
var elementsBeingSet = new List<elementType>();
Type elementType = GetElementType(); // get this type at runtime
Type listType = typeof(List<>);
Type combinedType = listType.MakeGenericType(elementType);
IList elements = (IList) Activator.CreateInstance(combinedType);