c# - C# 使用通过反射找到的类型作为泛型
问题描述
我正在尝试将 Type 用作泛型。本质上,我可以使用反射找到基于它的签名的类型。我现在需要做这样的事情:
Type theType = this.getMyType(mySignature);
string convertedData = mappingObj.mapIt<DataBase, theType>(myData);
但是,我不能theType
用作泛型。有没有办法做到这一点?
编辑:根据 Sohaib Jundi 的建议,我遇到了以下问题(非简化代码正在使用 Automapper 的 Map 方法):
typeof(IMapper).GetMethod("Map")
该行产生此错误:
'typeof(IMapper).GetMethod("Map")' threw an exception of type 'System.Reflection.AmbiguousMatchException'
我尝试使用 GetMethod 获得的方法是Map<TDestination, TSource>(TSource source)
,但我无法确定要调用以获取该方法的方法签名。作为参考,这里是映射方法所在的 automappers IMapper 类的链接。
解决方案
您还可以使用反射来调用泛型方法。它会是这样的:
string convertedData = (string)mappingObj.GetType().GetMethod("mapIt")
.MakeGenericMethod(typeof(DataBase), theType).Invoke(mappingObj, new object[] { myData });
推荐阅读
- datetime - 在 Power BI Desktop 中定义今天的日期
- java - java real 中的优先级会影响执行顺序吗?
- foreach - CMake Release和Debug运行不同的std :: for_each单线程/多线程c ++ 17
- javascript - React-Table useTable 未定义(无 Node.js)
- python - Altair:如何以预定义的缩放开始交互式标称条形图?
- c++ - C++ 指针和内存分配
- c++ - 使用 C++ 的可索引跳过列表实现
- javascript - 跨域索引数据库存储
- sql - 如果没有条件,Postgresql 左连接显示空值
- r - 有没有办法对一列中的变量进行分组并在第二列中获取另一个变量的比率?