如何从泛型定义和泛型参数中获取通用类型?

4

在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#中是否可能实现?提前感谢。
1个回答

4

没有typeof(List)这样的东西。不过,typeof(List<>)可以正常工作,并且是开放式泛型类型。然后你只需要使用:

var genericDefinition = typeof(List<>);
var genericArgument = typeof(string);
var concreteListType = genericDefinition.MakeGenericType(new[] {genericArgument});

你应该发现 concreteListTypetypeof(List<string>) 类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接