我正在尝试使用Type作为泛型。本质上,我能够使用反射根据其签名找到一个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)
,但是我无法确定要获取该方法而调用的方法签名。作为参考,这是Map方法所在的自动映射器IMapper类的链接。
您还可以使用反射来调用通用方法。就像这样:
string convertedData = (string)mappingObj.GetType().GetMethod("mapIt")
.MakeGenericMethod(typeof(DataBase), theType).Invoke(mappingObj, new object[] { myData });
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句