How to get generic type from generic definition an

2019-06-25 13:53发布

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?

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

标签: c# reflection
1条回答
Melony?
2楼-- · 2019-06-25 14:01

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});

and you should find that concreteListType is typeof(List<string>).

查看更多
登录 后发表回答