如何创建一个动态类型List< T> [英] How do I create a dynamic type List<T>

查看:106
本文介绍了如何创建一个动态类型List< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不希望我的列表是固定式的。而我要表的创建依赖于变量的类型。此代码不起作用:

 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.Collections.Generic;
命名空间ConsoleApplication3
{
类节目
{
静态无效的主要(字串[] args)
{

串的东西=苹果;
$ B $型B型= something.GetType();

名单,LT;类型>名单= NULL;

Console.ReadKey();

}
}
}



任何人可以告诉我什么样的变化,我需要以使它工作权做什么呢?我想列表的创建依赖于变量的东西


类型< DIV CLASS =h2_lin>解决方案

 字符串的东西=苹果; $ B $型B型= something.GetType(); 
型listType = typeof运算(名单<>)MakeGenericType(新[] {}型)。
IList的名单=(IList的)Activator.CreateInstance(listType);

这是如何创建静态未知类型的列表。但是请注意,你不能提静态列表的运行时类型。你必须使用非泛型类型,甚至对象。



不知道更多有关你要完成这是你能做的最好的东西。


I don't want my List to be of fixed type. Rather I want the creation of List to be dependent on the type of variable. This code doesn't work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            string something = "Apple";

            Type type = something.GetType();

            List<type> list = null;

            Console.ReadKey();

        }
    }
}

Can anybody tell me what changes I need to make in order to make it work right? I want the creation of list to be dependent on the type of variable something

解决方案

string something = "Apple";
Type type = something.GetType();
Type listType = typeof(List<>).MakeGenericType(new [] { type } );
IList list = (IList)Activator.CreateInstance(listType);

This is how you create a list of statically unknown type. But notice that you are unable to mention the runtime type of the list statically. You have to use a non-generic type or even object.

Without knowing more about what you want to accomplish this is the best you can do.

这篇关于如何创建一个动态类型List&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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