首页 > 解决方案 > 如何从泛型类型定义中获取类型参数名称?

问题描述

假设我有一个这样的泛型类型定义:

var type = typeof(IReadOnlyDictionary<,>)

我将如何获得泛型参数的类型参数名称?在上面的示例中,我正在寻找"TKey""TValue"

因为typeof(IList<>)我期待"T"

有没有办法使用反射来获取这些字符串?

标签: c#.netgenericsreflectionsystem.reflection

解决方案


您可以Type.GetGenericParameterConstraints为此使用:

var type = typeof(IReadOnlyDictionary<,>)
var names = type.GetGenericArguments().Select(x => x.Name);

看我的小提琴


推荐阅读