[英]How to get generic type from generic definition and generic arguments?
In C#, how can I construct generic type from generic definition and generic arguments like 在C#中,我如何从泛型定义和泛型参数中构造泛型类型
var genericDefinition = typeof(List);
var genericArgument = typeof(string);
// How can I get the Type instance representing List<string> from the 2 variables above?
In my usecase, the generic argument is dynamically resolved. 在我的用例中,泛型参数是动态解析的。 Is this possible in C#?
这可能在C#中吗? Thanks in advance.
提前致谢。
There's no such thing as typeof(List)
. 没有
typeof(List)
这样的东西。 However, typeof(List<>)
works fine, and is the open generic type. 但是,
typeof(List<>)
工作正常,并且是开放的泛型类型。 Then you just use: 然后你只需使用:
var genericDefinition = typeof(List<>);
var genericArgument = typeof(string);
var concreteListType = genericDefinition.MakeGenericType(new[] {genericArgument});
and you should find that concreteListType
is typeof(List<string>)
. 你会发现
concreteListType
是typeof(List<string>)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.