사용자 지정 클래스 인스턴스 비교를 구현할 때 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
가 출력 I가 내가 그것을 경우 B
클래스의 Equals
를 오버라이드 (override) 할 필요가 무엇인지 자신에게 물어 지금
one A
one B
one B+
입니다
Code = "one B+"
댓글을 달았습니다 이것이 비교에 아무런 영향을 미치지 않는 것 같습니다.
GetHasCode()
은 그러한 종류의 비교에 충분합니까?
가능한 복제본 [Equals()/GetHashCode()를 올바르게 구현 했습니까?] (http://stackoverflow.com/questions/5700099/have-i-implemented-equals-gethashcode-correctly) –