代码示例:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace TestObjectCopy { class Program { static void Main(string[] args) { Dog d1 = new Dog(); d1.Age = 2; d1.BirthDay = DateTime.Parse("2018-05-01"); d1.Name = "XiaoHei"; d1.ListHobby = new List<Hobby>(); d1.ListHobby.Add(new Hobby() { HobbyName = "吃" }); d1.ListHobby.Add(new Hobby() { HobbyName = "跑" }); Dog d2 = d1.ShallowClone(); //d2.Age = 3; d2.BirthDay = DateTime.Parse("2020-06-01"); d2.Name = "XiaoHuang"; Console.WriteLine(d1.Name+"===="+d1.Age+"===="+d1.BirthDay); Console.WriteLine(""); Console.WriteLine(d2.Name + "====" + d2.Age + "====" + d2.BirthDay); d2.ListHobby[0].HobbyName = "xxx"; Dog d3 = BinaryDeepCopy<Dog>(d1); d3.ListHobby.Remove(d3.ListHobby[0]); d3.ListHobby[0].HobbyName = "喝"; d3.ListHobby.Add(new Hobby() { HobbyName = "跳" }); d3.ListHobby.Add(new Hobby() { HobbyName = "睡" }); StringBuilder sb1 = new StringBuilder(); foreach (var item in d1.ListHobby) { sb1.Append( item.HobbyName+"|"); } Console.WriteLine(sb1.ToString()); StringBuilder sb2 = new StringBuilder(); foreach (var item in d2.ListHobby) { sb2.Append(item.HobbyName + "|"); } Console.WriteLine(sb2.ToString()); StringBuilder sb3 = new StringBuilder(); foreach (var item in d3.ListHobby) { sb3.Append(item.HobbyName + "|"); } Console.WriteLine(sb3.ToString()); Console.ReadKey(); } /// <summary> /// 二进制序列化的方式进行深拷贝 /// 确保需要拷贝的类里的所有成员已经标记为 [Serializable] 如果没有加该特性特报错 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static T BinaryDeepCopy<T>(T t) { //创建二进制序列化对象 BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream())//创建内存流 { //将对象序列化到内存中 bf.Serialize(ms, t); ms.Position = 0;//将内存流的位置设为0 return (T)bf.Deserialize(ms);//继续反序列化 } } } [Serializable] public class Dog { public string Name { get; set; } public int Age { get; set; } public DateTime BirthDay { get; set; } public List<Hobby> ListHobby { get; set; } public Dog ShallowClone() { return this.MemberwiseClone() as Dog; } } [Serializable] public class Hobby { public string HobbyName { get; set; } } }
深度copy