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

C# Use a Type found via reflection as a generic

我正在尝试将类型用作泛型。本质上,我可以使用反射找到基于其签名的类型。我现在需要做这样的事情:

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),但我无法确定要调用以获取该方法的方法签名。作为参考,这里是自动映射器 IMapper class 的 link,Map 方法所在的位置。

AutoMapper IMapper

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

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