是否可以将泛型与类型参数混合使用?比如有没有办法这样写代码:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
listOfLists.Add(new List<t>());
}
return listOfLists.ToList();
}
很明显,编译器不喜欢这样,但是有什么办法可以做到这一点吗?
请您参考如下方法:
要用反射来做到这一点,您必须从开放类型构造封闭泛型;然后用我们有的选项之一来构造它并进行反射。 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 的列表,这是必要的,因为我们在编译时不知道类型,所以为了使用您的新的通用列表,您可能需要再次使用反射。考虑是否值得 - 当然,这取决于您的要求。
