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

C# 內存管理深度解析(七):ICloneable 深拷貝與字符串特例

     編輯:關於C語言

問題回顧

引用類型字段淺拷貝導致副本共享子對象,修改相互影響。需深拷貝完全隔離。

ICloneable 標準實現


public class Shoe : ICloneable
{
    public string Color;
    public object Clone() => new Shoe { Color = (string)Color.Clone() };
}

public class Dude : ICloneable
{
    public string Name;
    public Shoe LeftShoe, RightShoe;

    public object Clone()
    {
        return new Dude
        {
            Name = (string)Name.Clone(),
            LeftShoe = (Shoe)LeftShoe.Clone(),
            RightShoe = (Shoe)RightShoe.Clone()
        };
    }
}

測試驗證


Dude bill = new Dude { Name = "Bill", LeftShoe = new Shoe { Color = "Blue" }, RightShoe = new Shoe { Color = "Blue" } };
Dude ted = (Dude)bill.Clone();
ted.Name = "Ted";
ted.LeftShoe.Color = ted.RightShoe.Color = "Red";

Console.WriteLine(bill); // Bill: Blue / Blue
Console.WriteLine(ted);  // Ted:  Red / Red

字符串特例:不可變引用類型

  • string 是引用類型,但不可變:任何「修改」操作都返回新實例。
  • 因此 string s1 = "abc"; string s2 = s1; s2 = "def"; 不會影響 s1。
  • string 實現了 ICloneable,Clone() 返回自身(因為不可變,無需複製)。
  • 內存中多個相同字面量可能指向同一實例(驻留池),但語義上安全。

最佳實踐建議

  1. 實現 ICloneable 時文檔說明是深拷貝還是淺拷貝(接口未強制規定)。
  2. 優先考慮不可變類型(readonly 字段、init 屬性、record),從根本避免拷貝問題。
  3. 深拷貝通用方案:序列化反序列化(JSON/Binary/Protobuf)、MemberwiseClone + 手動深拷貝引用字段、Expression 樹構建拷貝委託。
  4. 避免在集合/字典鍵中使用可變引用類型,除非實現值語義(IEquatable、GetHashCode 穩定)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved