2017-09-01 74 views
0

我複製了具有相同屬性但不是全部屬性的Class2中的Class1。在我的上下文中,我有一個Class1 obj(o1)用值初始化,我想用一個Class2 obj(o2)的值更改某些值,而不會丟失o1數據(值不在o2中)。手動,我需要重新賦值o2的值,所以我想找到一個像映射類的自動方式。映射2個具有相同屬性的類

類:

public class Class1 
{ 
    public bool Property1; 
    public int Property2; 
    public string Property3; 
    public bool Property4; 
    public int Property5; 
    public string Property6; 
    public bool Property7; 
    public int Property8; 
    public string Property9; 
    public bool Property10; 
    public int Property11; 
    public string Property12; 
    public bool Property13; 
    public int Property14; 
    public string Property15; 
    public bool Property16; 
    public int Property17; 
    public string Property18; 
    public bool Property19; 
    public int Property20; 
} 

public class Class2 
{ 
    public bool Property1; 
    public int Property2; 
    public string Property3; 
    public bool Property7; 
    public int Property8; 
    public string Property9; 
    public bool Property10; 
    public int Property11; 
    public string Property12; 
    public bool Property13; 
    public int Property14; 
    public string Property15; 
    public bool Property16; 
    public int Property17; 
    public string Property18; 
    public bool Property19; 
    public int Property20; 

    public Class1 ToClass1() 
    { 
     return new Class1() 
     { 
      Property1 = Property1, 
      Property2 = Property2, 
      Property3 = Property3, 
      Property7 = Property7, 
      ... 
      Property20 = Property20 
     }; 
    } 
} 

如果我做ToClass1(),我失去了Property4,Property5和O1的Property6的值。

我現在在做什麼:

// o1 and o2 are initialised with values. 
o1.Property1 = o2.Property1; 
o1.Property2 = o2.Property2; 
o1.Property3 = o2.Property3; 
o1.Property7 = o2.Property7; 
... 
o1.Property20 = o2.Property20; 
+0

是否Automapper不是一個選項? – pinkfloydx33

+0

你仍然可以填充property4,5,6 – Amit

回答

相關問題