2013-01-04 165 views
1

我想知道是否有人可以推薦一種可以在.NET2.0中工作的Automapper替代方案。.Net 2.0中的對象映射對象

我有一個dll描述了一個相當複雜的結構。 dll位於webservice的兩端,但是當通過webservice檢索數據時,名稱空間會阻止對象的直接映射,所以我不得不求助於編碼映射類。

我整合了Automapper,它完全按照我的意思,但它不會與.NET2.0一起使用。我需要使用.NET2.0,因爲有幾百個遠程機器可以運行客戶端軟件,並且它們僅限於.NET2.0。

任何幫助,將不勝感激。

+0

您可以移動到至少NET 3.0?使用WCF,你可以共享一個DataContract對象的公共DLL,允許你嚴格重用同一個對象。 –

+0

不能使用任何東西,但.NET2.0。可能需要使用Mono和.NET Compact(對於CE5.0),所以我試圖讓解決方案儘可能簡單。 – Sparers

回答

1

由於這是2.0,我猜這是一個常規的基於wsdl的web服務,通​​過XmlSerializer(不同於默認使用DataContractSerializer的WCF)工作。如果是這樣的話,你應該能夠使用XmlSerializer兩次:

FromType fromObj = ...; 
ToType toObj; 
using(var ms = new MemoryStream()) 
{ 
    new XmlSerializer(typeof(FromType)).Serialize(ms, fromObj); 
    ms.Position = 0; 
    toObj = (ToType) new XmlSerializer(typeof(ToType)).Deserialize(ms); 
} 

也許並不理想,但只要類型兼容它應該工作。

令人沮喪的是,WCF工具內置了對重用現有類型定義的支持,以避免這種重複。但顯然,這是3.0。

+0

謝謝馬克,試過這個,但是轉換隻是部分的,因爲子結構沒有正確映射。與源xml中的名稱空間引用有關嗎? – Sparers

0

根據結構的複雜程度,您可以使用獲取第一個對象的屬性列表,並將相關值設置爲具有相同名稱的第二個對象屬性。

如果你的結構只有簡單的屬性,它將是高效的。

0

在這種情況下,反射是你最好的朋友。

下面是一個財產複印機的粗略實施。您只需要新建一個目標類型的實例,並將其傳遞給具有所有屬性值設置的源實例。

編輯:正如馬克已經指出的,這隻會在瑣碎的屬性映射方面做伎倆。帶上一粒鹽吧。

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Reflection; 

namespace StackOverflow 
{ 
    public static class ReflectionHelper 
    { 
     public static void CopyPropertyValues(object source, object target) 
     { 
      if (source == null) throw new ArgumentNullException("source"); 
      if (target == null) throw new ArgumentNullException("target"); 

      var sourceType = source.GetType(); 
      var targetType = target.GetType(); 
      var sourceProperties = sourceType.GetProperties(); 

      foreach (var sourceProperty in sourceProperties) 
      { 
       if (sourceProperty.CanRead) 
       { 
        var targetProperties = targetType.GetProperties(); 

        foreach (var targetProperty in targetProperties) 
        { 
         if (targetProperty.Name == sourceProperty.Name && 
          targetProperty.PropertyType == sourceProperty.PropertyType) 
         { 
          if (targetProperty.CanWrite) 
          { 
           var value = sourceProperty.GetValue(source, null); 

           targetProperty.SetValue(target, value, null); 
          } 

          break; 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+0

這隻適用於簡單的值。在最真實的情況,你可能有處理列表,數組,字典等等 - 你可能不得不重新映射子對象(其將在同一時間內可更換式),以及重新映射遺產。 –