c# – 如何使用Automapper将对象映射到未知目标类型?
发布时间:2020-12-15 18:15:50 所属栏目:百科 来源:网络整理
导读:请考虑以下情形.我有许多共享一个公共基类的类,我为每个派生类定义了一个automapper映射.像这样的东西: class A : Base {}class B : Base {}class ContractA : ContractBase {}class ContractB : ContractBase {}void Foo(){ Mapper.CreateMapA,ContractA()
请考虑以下情形.我有许多共享一个公共基类的类,我为每个派生类定义了一个automapper映射.像这样的东西:
class A : Base {} class B : Base {} class ContractA : ContractBase {} class ContractB : ContractBase {} void Foo() { Mapper.CreateMap<A,ContractA>(); Mapper.CreateMap<B,ContractB>(); } 到现在为止还挺好.但现在我想创建一个这样的方法: ContractBase Foo() { Base obj = GetObject(); return Mapper.??? } 问题是所有AutoMapper的Map变体都要求我在编译时知道目标类型,或者在运行时使用该类型的对象.这非常令人沮丧,因为我为每种源类型只定义了一个映射. AutoMapper应该只能在给定源类型的情况下推断目标类型. 这有什么好办法吗?我想避免创建将源类型映射到目标类型的字典.虽然这可行,但这意味着我基本上必须为每种源类型定义两个映射. 解决方法
您可以访问存储在AutoMapper中的映射:
ContractBase Foo() { Base obj = GetObject(); var sourceType = obj.GetType(); var destinationType = Mapper.GetAllTypeMaps(). Where(map => map.SourceType == sourceType). // Note: it's assumed that you only have one mapping for the source type! Single(). DestinationType; return (ContractBase)Mapper.Map(obj,sourceType,destinationType); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |