1. 程式人生 > >深度複製與淺複製

深度複製與淺複製

淺複製

淺複製會連引用型別一起復制

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為一個值,不是引用型別,所以此時的複製為深度複製