是否无法动态使用泛型?

Vic*_*ues 10 c# generics

我需要在运行时创建一个使用泛型的类的实例,比如class<T>,在不知道它们将具有的类型T的情况下,我想做类似的事情:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
    }

    return lists;
}
Run Code Online (Sandbox Code Playgroud)

......但我做不到.我认为不可能在通用括号内的C#中写入一个类型变量.还有另一种方法吗?

Jon*_*eet 18

你不能这样做 - 泛型的主要是编译时类型安全 - 但你可以用反射来做:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        Type genericList = typeof(List<>).MakeGenericType(type);
        lists.Add(type, Activator.CreateInstance(genericList));
    }

    return lists;
}
Run Code Online (Sandbox Code Playgroud)