序列化与反序列化实现深度复制。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { User usr1 = new User(); usr1.addr = new addressFormat("ykwang1"); User usr2 = usr1.Clone(); usr2.addr.address = "ykwang2"; Console.Write(usr1.addr.address); User usr3 = usr1.Clone(true); usr3.addr.address = "ykwang3"; Console.Write(usr1.addr.address); Console.ReadKey(); } } [Serializable] public class User : ICloneable { public string name; public string desc; public string remark; public addressFormat addr; public User() { } protected User(User u) { name = u.name; desc = u.desc; remark = u.remark; } object ICloneable.Clone() { return base.MemberwiseClone(); } public User Clone() { return base.MemberwiseClone() as User; //return new User(this); } public User Clone(bool IsDeepCopy) { using (MemoryStream ms = new MemoryStream(1000)) { BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone)); bf.Serialize(ms, this); ms.Seek(0, SeekOrigin.Begin); User u = bf.Deserialize(ms) as User; ms.Close(); return u; } } } [Serializable] public class addressFormat { public string address; public addressFormat(string addtest) { address = addtest; } } }
另外可使用传统的new关键字实现深度复制,如果实现一个不可序列化的类的深度复制的统一模板,则需要采用递归跟new关键字去实现。