决定运行时的类型并将其应用于泛型类型 - 我该怎么做? [英] Deciding on type in the runtime and applying it in generic type - how can I do this?

查看:13
本文介绍了决定运行时的类型并将其应用于泛型类型 - 我该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a strongly type list and decide the type in runtime. This is my code.I thought it should work, but it doesn't :)

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

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

would you have any ideat how to create a strongly typed list whose type I will decide in runtime ?

重复:这里是其他版本:

Duplicate: here are other versions:

推荐答案

Use 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 来保存结果 - 因为您不知道将在运行时使用的实际类型.

You have to use IList to keep the result - because you don't know the actual type that will be used at runtime.

对于具有多个类型参数的泛型类型,您可以使用类似Dictionary<,>.

For generic types with more than one type parameter you would use something like Dictionary<,>.

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

这篇关于决定运行时的类型并将其应用于泛型类型 - 我该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆