SDK 文件:This method determines equality using the default equality comparer EqualityComparer.Default for T
T 實作 IEquatable<T> → 使用其 EqualsObject.Equals / Object.GetHashCode (參考比較)
IList products = new List();
products.Add(GetProduct("1412")); // 新實例 A
products.Remove(GetProduct("1412")); // 新實例 B (不同參考)
// 參考不相等 → Remove 失效 → Count 仍為 1
GetProduct 每次回傳新實例,導致「不死物件」。
public class Product : IEquatable
{
public string ID { get; private set; }
public Product(string id) { ID = id; }
public bool Equals(Product other)
{
return other != null && this.ID == other.ID;
}
public override bool Equals(object obj) => Equals(obj as Product);
public override int GetHashCode() => ID.GetHashCode();
}
public class Product
{
public string ID { get; private set; }
public Product(string id) { ID = id; }
public override bool Equals(object obj)
{
return obj is Product other && this.ID == other.ID;
}
public override int GetHashCode() => ID.GetHashCode();
}
Equals/GetHashCode 或實作 IEquatable<T>GetHashCode 必須與 Equals 一致 (相等物件 HashCode 必相同)