如何从泛型类型定义中获取类型参数名称?

How do I get the typeparam names from a generic type definition?

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

var type = typeof(IReadOnlyDictionary<,>)

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

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

有什么方法可以使用反射来获取这些字符串吗?

您可以为此使用 Type.GetGenericParameterConstraints

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

查看我的fiddle