相較於淺拷貝,深拷貝會依照來源物件為原型,建立一個全新的物件,並對所有欄位(無論值類型、引用類型、靜態或非靜態)執行逐位複製與遞迴複製,確保新物件與原物件完全獨立。
ICloneable 僅定義一個 Clone() 方法,回傳 object。實作時可選擇淺層或深層複製。深層複製需確保所有巢狀物件皆為新實例。
public class Person : ICloneable
{
public int Age { get; set; }
public string Address { get; set; }
public Name Name { get; set; }
public object Clone()
{
Person tem = new Person();
tem.Address = this.Address; // string 為不可變,直接指派即可
tem.Age = this.Age; // 值類型直接複製
tem.Name = new Name(this.Name.FristName, this.Name.LastName); // 手動新建引用類型
return tem;
}
}
public class Name
{
public Name(string frisName, string lastName)
{
FristName = frisName;
LastName = lastName;
}
public string FristName { get; set; }
public string LastName { get; set; }
}
痛點:若類別擁有數十個引用類型欄位,手動逐一新建將極其繁瑣,這也是引入序列化或 Expression Tree 方案的動機。