如何从泛型定义和泛型参数中获取泛型类型? [英] How to get generic type from generic definition and generic arguments?

查看:64
本文介绍了如何从泛型定义和泛型参数中获取泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,如何从泛型定义和泛型参数中构造泛型类型

In C#, how can I construct generic type from generic definition and generic arguments like

var genericDefinition = typeof(List);
var genericArgument = typeof(string);
// How can I get the Type instance representing List<string> from the 2 variables above?

在我的用例中,泛型参数是动态解析的.这在 C# 中可能吗?提前致谢.

In my usecase, the generic argument is dynamically resolved. Is this possible in C#? Thanks in advance.

推荐答案

没有 typeof(List) 这样的东西.但是, typeof(List<>) 工作正常,并且是开放的泛型类型.然后你只需使用:

There's no such thing as typeof(List). However, typeof(List<>) works fine, and is the open generic type. Then you just use:

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

你应该发现concreteListTypetypeof(List).

这篇关于如何从泛型定义和泛型参数中获取泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆