Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在运行时决定类型并在泛型类型中应用它-我如何做到这一点?_C#_Types - Fatal编程技术网

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);