2015-04-17 66 views
2

我一直在使用AutoMapper在接口和該接口的具體實現之間進行映射。我假設如果我傳遞給AutoMapper的Map<TDestination>方法的類型與返回類型相同,則返回原始對象(作爲一種短路操作)。我的假設是錯誤的:的確,看後我發現這個方法的文件明確規定:我可以使AutoMapper有時返回相同的對象嗎?

執行從源對象映射到一個新目的地對象。源類型是從源對象中推斷出來的。 (粗體重點煤礦)

我敲了這個快速控制檯應用程序,只是爲了驗證:

using System; 
using AutoMapper; 

namespace ConsoleApplication 
{ 
    class Program 
    { 
     interface IFoo 
     { 
      string Bar { get; } 
     } 

     class Foo : IFoo 
     { 
      public string Bar { get; set; } 
     } 

     static void Main(string[] args) 
     { 
      Mapper.CreateMap<IFoo, Foo>(); 
      IFoo a = new Foo { Bar = "baz" }; 
      Foo b = Mapper.Map<Foo>(a); 
      Console.WriteLine(Object.ReferenceEquals(a, b)); // false 
     } 
    } 
} 

現在,我知道這種行爲,我可以圍繞它優化我的特殊用例,但我想知道是否有另一種使用AutoMapper的方法,它將以上述方式「短路」(即,如果類型與我想要的目標類型相同,請將原始對象給我) ?

回答

5

您可以使用Mapper.Map<TSource,TDestination>(source, destination)過載。

Foo b = new Foo(); 
Mapper.Map<IFoo,Foo>(a,b); 

AutoMapper將使用b而不是建立一個新的對象。總體而言,你可以使用周圍Mapper.Map的包裝,這種替代方式可以得到更好的(未測試):

public class MyMapper 
{ 

     public static TDestination Map<TDestination>(object source) where TDestination : class 
     { 
      if(source is TDestination) 
      { 
       return (TDestination) source; //short-circuit here 
      } 

      return Mapper.Map<TDestination>(source); 
     } 


     public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination) 
     { 
      return Mapper.Map<TSource, TDestination>(source, destination); 
     } 
} 
+1

代替'typeof運算(TDestination).IsAssignableFrom == source.GetType()的'我會做少嚴格的來源是TDestination'。你的方法不適用於接口,'=='會返回false。 –

+0

謝謝你斯科特。我更新了樣本以反映您的驚人建議。 –

+0

另一個建議是,如果你使用'is',你應該像第一個例子那樣直接進行轉換,不要像第二個例子那樣使用'as'。如果演員失敗,就不需要額外的邏輯'as',因爲你已經知道'as'將會從'is'檢查中成功。 –

相關問題