浅度复制:只是复制类的值类型字段和引用类型字段的引用
深度复制:即完全复制过来,不管里面的值类型字段还是引用类型字段,是构成一个全新的一模一样的对象。
代码:
[Serializable] public class PersonInfo { public string Name{get;set;} public int Age{get;set;} }
[Serializable] public class Person : ICloneable { public PersonInfo PersonInfo { get; set; } public Person(PersonInfo personInfo) { this.PersonInfo = personInfo; } /// <summary> /// 浅度克隆 /// </summary> /// <returns></returns> public Person ShallowClone() { return this.MemberwiseClone() as Person; } /// <summary> /// 深度复制(实现ICloneable接口的方法) /// </summary> /// <returns></returns> public object Clone() { PersonInfo perInf = new PersonInfo { Name = this.PersonInfo.Name, Age = this.PersonInfo.Age }; Person per = new Person(perInf); return per; } /// <summary> /// 第二种深度复制 /// </summary> /// <returns></returns> public Person DeepClone() { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, this); ms.Position = 0; return (Person)formatter.Deserialize(ms); } } }