首页 > 代码库 > 序列化实现深拷贝(小计)
序列化实现深拷贝(小计)
class Program { static void Main(string[] args) { var people1 = new People(); people1.Age = 18; people1.IdCard = "410225"; var departMent = new Department() { Name = "计算机" }; people1.departMent = departMent; var people2 = people1.Clone(); Console.WriteLine(people2.Age); Console.WriteLine(people2.IdCard); Console.WriteLine(people2.departMent.Name); Console.WriteLine("变化啦!"); people1.Age = 18; people1.IdCard = "410225"; departMent.Name = "金融"; Console.WriteLine(people2.Age); Console.WriteLine(people2.IdCard); Console.WriteLine(people2.departMent.Name); Console.ReadLine(); } } [Serializable] public class People { public int Age{get;set;} public string IdCard{get;set;} public Department departMent{get;set;} public People Clone() { using (Stream ms = new MemoryStream()) { IFormatter forma = new BinaryFormatter(); forma.Serialize(ms, this); ms.Seek(0, SeekOrigin.Begin); return forma.Deserialize(ms) as People; } } } [Serializable] public class Department { public string Name{get;set;} }
实现了深度拷贝,不会因为Department中的Name变化而影响Department中的Name值
序列化实现深拷贝(小计)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。