首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 進階:淺拷貝與深拷貝的實現方式與 ICloneable 介面應用

     編輯:關於C語言

淺拷貝與深拷貝的核心差異

相較於淺拷貝,深拷貝會依照來源物件為原型,建立一個全新的物件,並對所有欄位(無論值類型、引用類型、靜態或非靜態)執行逐位複製與遞迴複製,確保新物件與原物件完全獨立。

C# 實現深拷貝的三種常見方法

  1. 實作 ICloneable 介面,自訂 Clone 邏輯(最靈活,但需手動處理每個引用欄位)。
  2. 序列化與反序列化(利用 BinaryFormatter 或 JSON 序列化,自動處理完整物件圖)。
  3. Expression Tree 動態建構複製委派(高效能,適合大量物件複製)。

ICloneable 介面詳細說明

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 方案的動機。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved