在运行时决定类型和泛型类型应用它 - 我该怎么办呢? [英] Deciding on type in the runtime and applying it in generic type - how can I do this?

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

问题描述

我想创建一个强类型列表,并决定在运行时的类型。这是我的code.I认为它应该工作,但它不会:)

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

请问您有什么ideat如何创建一个强类型的列表,它的类型,我会在运行时决定?

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

复制:这里有其他的版本:

Duplicate: here are other versions:

推荐答案

使用 Type.MakeGenericType(类型[])

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.

有关泛型类型的,你会使用类似词典&LT多个类型的参数;,&GT;

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

又见<一个href=\"http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx\">http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

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

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