How to get generic type from generic definition an

2019-06-25 14:03发布

问题:

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.

回答1:

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>).



标签: c# reflection