如何创建动态类型List <T>

Jag*_*ggu 10 .net c# reflection

我不希望我的列表是固定类型.相反,我希望List的创建依赖于变量的类型.此代码不起作用:

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我需要做些什么改变才能让它正常工作?我希望创建list依赖于变量的类型something

usr*_*usr 40

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

这是您创建静态未知类型列表的方法.但请注意,您无法静态提及列表的运行时类型.您必须使用非泛型类型甚至对象.

在不了解您想要实现的目标的情况下,这是您能做的最好的事情.

  • @Jaggu不,`var`不会像你想的那么做.它不会给你一个变量类型`List <Apple>`因为`var`是一个静态类型构造. (2认同)

svi*_*ick 6

我想要类型安全,但我需要动态类型安全.

如果您的意思是希望运行时类型安全,则可以List<T>使用反射创建(请参阅usr的答案)dynamic,然后将其视为非泛型IList.

使用dynamic,它看起来像这样:

static List<T> CreateListByExample<T>(T obj)
{
    return new List<T>();
}

…

object something = "Apple";

IList list = CreateListByExample((dynamic)something);

list.Add(something); // OK

list.Add(42);        // throws ArgumentException
Run Code Online (Sandbox Code Playgroud)