【发布时间】:2017-09-14 15:05:46
【问题描述】:
在我项目的某个地方,我需要创建一个具体的泛型类型,将泛型类型定义(带有单个参数)和该参数的类型作为参数。
为此,我编写了一个方法,非常简单:
Type MakeGenericType(Type definition, Type parameter)
{
return definition.MakeGenericType(parameter);
}
但是,在某些时候,我需要使用给定的元素类型 T 创建一个类型,例如 List<List<T>>。虽然我可以使用我的方法创建类型 List<List<T>>,但随后尝试从中创建具体类型 List<List<int>> 失败 - 请参见下面的代码:
var genericList = MakeGenericType(typeof(List<>), typeof(List<>)); // success
MakeGenericType(genericList, typeof(int)); // exception
“System.InvalidOperationException”类型的未处理异常 发生在 mscorlib.dll 中
附加信息: System.Collections.Generic.List`1[System.Collections.Generic.List`1[T]] 不是 GenericTypeDefinition。 MakeGenericType 只能被调用 Type.IsGenericTypeDefinition 为 true 的类型。
此外,以下调用甚至不会编译:
MakeGenericType(typeof(List<List<>>), typeof(int));
我检查了this question 关于IsGenericTypeDefinition 和ContainsGenericParameters 之间的区别。但是,我仍然不知道如何处理像genericList 这样的类型对象。
显然,使用反射我可以构造一个类型对象,这与它无关——这让我很困惑。
所以问题是,如何从泛型创建具体类型,其中包含泛型类型定义作为参数?有可能吗?
【问题讨论】:
标签: c# generics reflection