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



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

var type = typeof(IReadOnlyDictionary<,>)

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

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

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

您可以使用Type.GetGenericParameterConstraints

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

看我的小提琴。

最新更新