c# - 如何从泛型类型定义中获取类型参数名称?
问题描述
假设我有一个这样的泛型类型定义:
var type = typeof(IReadOnlyDictionary<,>)
我将如何获得泛型参数的类型参数名称?在上面的示例中,我正在寻找"TKey"
和"TValue"
因为typeof(IList<>)
我期待"T"
有没有办法使用反射来获取这些字符串?
解决方案
您可以Type.GetGenericParameterConstraints
为此使用:
var type = typeof(IReadOnlyDictionary<,>)
var names = type.GetGenericArguments().Select(x => x.Name);
看我的小提琴。
推荐阅读
- amazon-ec2 - 有什么方法可以控制 AWS SQS 的速度
- oracle - 通过任何可选字段(如名字、地址等)搜索客户 - 性能问题
- c# - 如何使使用数据库的测试更快?
- bash - 在 shell 脚本上添加用法
- php - php 7 及更高版本中 mcrypt_decrypt 的替代解决方案是什么?
- php - 删除方括号并根据上下文保留文本
- javascript - Ngrx Angular - 在简单对象上检测到不可序列化的动作
- django - 表单中的 Django 小部件无法正常工作
- git - VSCode在文件保存时将CRFL更改为LF,即使没有,git也会记录更改
- adonis.js - Adonis 在分页查询中使用 getter 失败