假設你有2類,像這樣:.NET/C#中是否有任何內容在對象之間複製值?
public class ClassA {
public int X { get; set; }
public int Y { get; set; }
public int Other { get; set; }
}
public class ClassB {
public int X { get; set; }
public int Y { get; set; }
public int Nope { get; set; }
}
現在想象你有每個類的一個實例,您想要將其值從複製到b中。有沒有像MemberwiseClone那樣複製屬性名稱匹配的值(當然也是容錯的 - 一個有get,另一個是集合等)?
var a = new ClassA(); var b = new classB();
a.CopyTo(b); // ??
像JavaScript這樣的語言非常容易。
我猜答案是否定的,但也許有一個簡單的選擇。我已經寫了一個反射庫來做到這一點,但是如果在較低的層次上嵌入到C#/ .NET中,可能會更有效率(以及爲什麼重新發明輪子)。
看看AutoMapper:http://lostechies.com/jimmybogard/2009/01/23/automapper-the-object-object-mapper/ –