是否可以将泛型与Type参数混合使用?例如,有没有办法编写这样的代码:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
listOfLists.Add(new List<t>());
}
return listOfLists.ToList();
}
显然,编译器不喜欢这样,但有没有办法实现这一点?
答案 0 :(得分:4)
要使用反射执行此操作,必须从open类型构造封闭的泛型类型;然后用反射中的一个选项构造它。 Activator.CreateInstance适用于此:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
Type requestedTypeDefinition = typeof(List<>);
Type genericType = requestedTypeDefinition.MakeGenericType(t);
IList newList = (IList)Activator.CreateInstance(genericType);
listOfLists.Add(newList);
}
return listOfLists;
}
请注意,您正在从此方法返回非泛型IList
的列表,这是必要的,因为我们在编译时不知道类型,因此为了使用新的通用列表,你可能需要再次使用反射。考虑它是否值得 - 当然,这取决于您的要求。