C#将通过反射找到的类型用作泛型

ste*_*ris 4 c# generics reflection automapper

我正在尝试使用Type作为泛型。本质上,我能够使用反射根据其签名找到一个Type。我现在需要执行以下操作:

Type theType = this.getMyType(mySignature);
string convertedData = mappingObj.mapIt<DataBase, theType>(myData);
Run Code Online (Sandbox Code Playgroud)

但是,我不能theType用作泛型。有没有办法做到这一点?

编辑:根据Sohaib Jundi的建议,我遇到了以下问题(非简化代码正在与Automapper的Map方法一起使用):

typeof(IMapper).GetMethod("Map")
Run Code Online (Sandbox Code Playgroud)

该行产生此错误:

'typeof(IMapper).GetMethod("Map")' threw an exception of type 'System.Reflection.AmbiguousMatchException'
Run Code Online (Sandbox Code Playgroud)

我尝试通过GetMethod获取的方法是Map<TDestination, TSource>(TSource source),但是我无法确定要获取该方法而调用的方法签名。作为参考,这是Map方法所在的自动映射器IMapper类的链接。

AutoMapper IMapper

Soh*_*ndi 7

您还可以使用反射来调用通用方法。就像这样:

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