在C#中,我如何通过泛型定义和泛型参数构造通用类型,例如
var genericDefinition = typeof(List);
var genericArgument = typeof(string);
// How can I get the Type instance representing List<string> from the 2 variables above?
在我的使用场景中,通用参数是动态解析的。在C#中是否可能实现?提前感谢。
在C#中,我如何通过泛型定义和泛型参数构造通用类型,例如
var genericDefinition = typeof(List);
var genericArgument = typeof(string);
// How can I get the Type instance representing List<string> from the 2 variables above?
没有typeof(List)
这样的东西。不过,typeof(List<>)
可以正常工作,并且是开放式泛型类型。然后你只需要使用:
var genericDefinition = typeof(List<>);
var genericArgument = typeof(string);
var concreteListType = genericDefinition.MakeGenericType(new[] {genericArgument});
你应该发现 concreteListType
是 typeof(List<string>)
类型。