首页 > 解决方案 > 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 类的链接。

自动映射器

标签: c#genericsreflectionautomapper

解决方案


您还可以使用反射来调用泛型方法。它会是这样的:

string convertedData = (string)mappingObj.GetType().GetMethod("mapIt")
    .MakeGenericMethod(typeof(DataBase), theType).Invoke(mappingObj, new object[] { myData });

推荐阅读