动态使用泛型是不可能的吗? [英] Is it impossible to use Generics dynamically?
本文介绍了动态使用泛型是不可能的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在运行时创建一个使用泛型的类的实例,比如 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;
}
这篇关于动态使用泛型是不可能的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文