序列化与反序列化实现深度复制。
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关键字去实现。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步