2014-12-30 47 views
0

我使用需要將轉換器數據類型寫入另一個的應用程序。例如:.Net中的映射

public class WcfContactName 
{ 
public string FirstName {get; set;} 
public string LastName {get; set;} 
} 
public class IosContactName 
{ 
public string FirstName {get; set;} 
public string LastName {get; set;} 
} 

我必須寫一個功利類(AutoMapper),映射屬性類條件是其中自動執行: - 具有相同的名稱(忽略下/上殼體) - 具有相同的數據類型 我必須爲無限嵌套級別製作映射屬性。您還需要在轉換期間允許某些屬性被忽略。編寫代碼時遵循測試驅動的開發流程。誰能幫我?謝謝

+0

你有什麼具體問題?這太寬泛了。你實際上是要求別人寫你的映射器。 –

+1

你標記了你的文章'Automapper'。這是一個開源項目,已經完成了你所概述的內容。 –

回答

0

您需要使用ReflectionSystem.Reflection命名空間)機制。對於這兩種映射類型,您需要獲取有關類型(TypeInfo類)及其屬性(PropertyInfo類)的信息,然後爲您的映射構建邏輯。通過使用PropertyInfo類,您可以獲取名稱和屬性類型。 Reflection允許您獲取和設置對象屬性的值,以便您能夠構建您的映射器。它還允許你調用方法,構造函數,並執行其他操作。

0
public class AutoMap 
    { 
     public List<string> BlackList = new List<string>(); 

     //public void Map(object o1, object o2)   
     public void Map<K, T>(K o1, T o2) 
     { 
      for (int i = 0; i < BlackList.Count; i++) 
      { 
       BlackList[i] = BlackList[i].ToUpper(); 
      } 
      //BlackList.ForEach(delegate(string s) { s = s.ToUpper(); }); 

      //if (o1 == null || o2 == null) 
      // return;      

      //Type t1 = o1.GetType(); 
      Type t1 = typeof(K); 
      IList<PropertyInfo> props1 = new List<PropertyInfo>(t1.GetProperties()); 

      //Type t2 = o2.GetType(); 
      Type t2 = typeof(T); 
      IList<PropertyInfo> props2 = new List<PropertyInfo>(t2.GetProperties());    

      for (int i = 0; i < props1.Count; i++) 
      { 
       object propValue1 = (o1 != null ? props1[i].GetValue(o1, null) : null); 

       string Name = props1[i].Name; 
       Type tt1 = props1[i].PropertyType; 

       for (int j = 0; j < props2.Count; j++) 
       { 

        if (!BlackList.Contains(props2[j].Name.ToUpper()) 
         && props2[j].Name.ToUpper() == Name.ToUpper()) 
        { 
         object propValue2 = (o2 != null ? props2[j].GetValue(o2, null) : null); 
         Type tt2 = props2[j].PropertyType; 

         if (tt1.Equals(tt2)) 
         { 
          if (o2!= null) 
           props2[j].SetValue(o2, propValue1, null); 
         } 
         else 
         { 
          if (tt1.IsClass && tt2.IsClass) 
          {                      

           MethodInfo mi = this.GetType().GetMethod("Map").MakeGenericMethod(new Type[] { tt1, tt2 }); 
           mi.Invoke(this, new object[] { propValue1, propValue2 }); 

           props2[j].SetValue(o2, propValue2, null); 
          } 
         } 


         break; 
        } 
       } 
      } 
     } 


    }