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

C# 呼叫 Remove 失效分析(一):不死物件現象重現與問題定義

     編輯:關於C語言

現象:集合移除後物件仍存在


// Code #01
IList products = new List();
products.Add(GetProduct("1412"));
products.Remove(GetProduct("1412"));
Console.WriteLine(products.Count); // 輸出 1 (預期 0)

Product 類別定義


// Code #02
class Product
{
    public Product(string id) { m_ID = id; }
    private string m_ID;
    public string ID { get { return m_ID; } }
    public override string ToString() { return "ID: " + m_ID; }
}

GetProduct 簽名


// Code #03
public static Product GetProduct(string id); // 從資料庫讀取並建構新實例

驗證代碼


// Code #04
Console.WriteLine(products.Count); // 驗證是否真正移除

問題本質

  • Add 加入實例 A
  • Remove 傳入實例 B (同 ID 不同參考)
  • List.Remove 使用預設相等比較 (參考相等)
  • 實例 A ≠ 實例 B → 移除失敗

下一步

檢視 SDK 文件確認 List<T>.Remove 相等比較機制,尋找解決方案 (詳見第 2 部分)。

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