深度复制与浅复制
浅复制
浅复制会连引用类型一起复制
public class Content { public int val; } public class Cloner { public Content MyContent = new Content(); public Cloner(int newVal) => MyContent.val = newVal; public object GetCopy() => MemberwiseClone(); } class Program { static void Main(string[] args) { Cloner Test1 = new Cloner(10); Cloner Test2 = (Cloner)Test1.GetCopy(); Test1.MyContent.val = 5; Console.WriteLine(Test2.MyContent.val); Console.ReadKey(); } }
此时,此处输出为5
表明Test2和Test1的引用类型一致
深度复制
为了解决上述引用类型的问题,可通过实现ICloneable接口中的方法Clone()进行深度复制
public object Clone() { Cloner cloner = new Cloner(MyContent.val); return cloner; } static void Main(string[] args) { Cloner Test1 = new Cloner(10); Cloner Test2 = (Cloner)Test1.Clone(); Test1.MyContent.val = 5; Console.WriteLine(Test2.MyContent.val); Console.ReadKey(); }
此时输出值为10
由于传入的MyContent.val为一个值,不是引用类型,所以此时的复制为深度复制