c# - 在运行时确定类型并将其应用到泛型类型中——我该怎么做?

标签 c# types

<分区>

我想创建一个强类型列表并在运行时决定类型。这是我的代码。我认为它应该可以工作,但它没有:)

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

您是否知道如何创建一个我将在运行时决定其类型的强类型列表?

重复:这里是其他版本:

最佳答案

使用 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

关于c# - 在运行时确定类型并将其应用到泛型类型中——我该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/326285/

相关文章:

c# - Entity Framework 6 Code First 查找表未填充

c# - 使用 log4net 设置 XmlConfigurator 公共(public)日志记录

python - python 中的智能类型转换

c# - 当类型仅在执行时已知时调用泛型函数

programming-languages - 什么是通用类型?

types - 解释器和静态类型检查

c# - 使用合并更新表并使用定义的表类型

c# - Unity ViewtoWorldPoint 不工作,我做错了什么?

C# XNA Box2d : What kind of joints for a ragdoll?

C++ OpenCV : Convert vector<vector<Point>> to vector<vector<Point2f>>