动态使用泛型是不可能的吗?
问题描述:
我需要在运行时创建一个使用泛型的类的实例,比如 class<T>
,之前不知道它们将拥有的类型 T,我想做这样的事情:
I need to create at runtime instances of a class that uses generics, like class<T>
, without knowing previously the type T they will have, I would like to do something like that:
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;
}
...但我不能.我认为在通用括号内用 C# 编写类型变量是不可能的.还有其他方法吗?
...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?
答
你不能那样做——泛型的要点主要是编译时类型安全——但你可以做到它带有反射:
You can't do it like that - the point of generics is mostly compile-time type-safety - but you can do it with reflection:
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;
}