實現自定義類實例比較時,我們是否應該覆蓋Equals
和GetHashCode
屬性?當比較對象時等於vs GetHashCode
在下面的代碼中我有一個類的集合。類別A
由ID
,類別B
-由Code
進行比較。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<I> bars = new List<I>();
bars.Add(new A() { Id = 1, Code = "one A" });
bars.Add(new B() { Id = 1, Code = "one B" });
bars.Add(new A() { Id = 1, Code = "one A+" });
bars.Add(new B() { Id = 1, Code = "one B" }); // Code = "one B+"
var distictBars = bars.Distinct();
foreach (var item in distictBars)
{
Debug.WriteLine(item.Code);
}
}
}
interface I
{
string Code { get; set; }
}
class A : I, IEquatable<A>
{
public int Id { get; set; }
public string Code { get; set; }
public bool Equals(A other)
{
// this is the ??? comparison
return this.Id == other.Id;
//return this.Code == other.Code;
}
public override bool Equals(object obj)
{
if (obj is A)
return this.Equals(obj as A);
else
return object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
// this is the wanted comparison
return this.Id;
}
}
class B : I, IEquatable<B>
{
public int Id { get; set; }
public string Code { get; set; }
public bool Equals(B other)
{
// this is the ??? comparison
return this.Id == other.Id;
}
public override bool Equals(object obj)
{
if (obj is B)
return this.Equals(obj as B);
else
return object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
// this is the wanted comparison
return this.Code.GetHashCode();
}
}
}
輸出是:
one A
one B
的情況下,評論Code = "one B+"
輸出
one A
one B
one B+
現在我問自己什麼,我應該在B
類,如果它覆蓋Equals
似乎這對比較沒有影響?
是GetHasCode()
重寫足夠的那種比較?
的可能重複[我有沒有正確實現的equals()/ GetHashCode()方法?(http://stackoverflow.com/questions/5700099/have-i-implemented-equals-gethashcode-correctly) – 2011-05-12 17:46:36