创建变量类型的列表 [英] Create list of variable type

查看:135
本文介绍了创建变量类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个特定类型的列表。

我要使用的列表格式,但我所知道的是一个System.Type的

该类型有是可变的。我怎样才能创建一个变量类型的列表?

我想类似这样code的东西。

 公共IList的createListOfMyType(类型的myType)
{
     返回新的List<&的myType GT;();
}


解决方案

您可以使用反思,这里是一个示例:

 键入MYTYPE = typeof运算(INT);    键入listGenericType = typeof运算(名单<>);    类型列表= listGenericType.MakeGenericType(MYTYPE);    ConstructorInfo CI = list.GetConstructor(新类型[] {});    清单< INT> listInt =(列表< INT>)ci.Invoke(新的对象[] {});

I am trying to create a list of a certain type.

I want to use the List notation but all I know is a "System.Type"

The type a have is variable. How can I create a list of a variable type?

I want something similar to this code.

public IList createListOfMyType(Type myType)
{
     return new List<myType>();
}

解决方案

You could use Reflections, here is a sample:

    Type mytype = typeof (int);

    Type listGenericType = typeof (List<>);

    Type list = listGenericType.MakeGenericType(mytype);

    ConstructorInfo ci = list.GetConstructor(new Type[] {});

    List<int> listInt = (List<int>)ci.Invoke(new object[] {});

这篇关于创建变量类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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