2015년 4월 10일 금요일

Equals를 재정의할 때 GetHashCode를 재정의하십시오.

ㆍ언어대상 : C#   ㆍ실행대상 : 윈도우(일반)   ㆍ작성자 : 이동현   ㆍ간단설명 : .NET 규칙입니다.  

1. 상황 :

클래스 정의시에  public 형식이 Object.Equals를 재정의하지만 Object.GetHashCode는 재정의하지 않는 경우가

비주얼 스튜디오에서 경고 메세지가 발생합니다.

 

2. GetHashCode의 역할 :

GetHashCode 는 현재 인스턴스를 기반으로 해싱 알고리즘 및 해시 테이블과 같은 데이터 구조체에 적합한 값을 반환합니다.
같은 형식의 동일한 두 개체가 같은 해시 코드를 반환해야 다음 형식의 인스턴스가 올바르게 작동한다고 할 수 있습니다.

 

3. GetHashCode 재 정의시 올바르게 작동하는 클래스

4. 문제 해결 쟁점

형식이 같은 두 개체의 경우 이들 개체에 대한 Equals의 구현이 true를 반환하는 경우 GetHashCode 구현이 같은 값을 반환하는지 확인해야 합니다.

 

5. StackOverFlow 참조

5-1 질문 : Why is it important to override GetHashCode?

5-2 답변 :

Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>, etc - since this is used (in the absense of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).

The GetHashCode() method should reflect the Equals logic; the rules are:

  • if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
  • if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.

In this case, it looks like "return FooId;" is a suitable GetHashCode() implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5) has a different hash-code to new Foo(5,3)):

int hash = 13; hash = (hash * 7) + field1.GetHashCode(); hash = (hash * 7) + field2.GetHashCode(); ... return hash;

Oh - for convenience, you might also consider providing == and != operators when overriding Equals and GethashCode.

 

5. 결론 : 3번의 내용을 사용하지 않을 것이라면, GetHashCode와 Equeal를 재 정의할 필요는 없습니다.

하지만 Equals를 정의한 이후에 GetHashCode는 반드시 재정의하고, 재정의에 필수 조건은 생성할 클래스에서 생성하는 객체가 동일할 경우에 같은 HashCode를 반환하도록 재정의해야 합니다.

 



해당 내용은 (주)데브존의 웹봇이 자동으로 저희 홈페이지와 API로 동기화한 내용입니다. 자세한 내용은 홈페이지 http://www.devzone.co.kr 또는 모바일 폰에서 http://devzone.co.kr을 접속 하여 확인해 보시기 비랍니다.
-  대표 전화 : 02) 2061 - 0753   - Fax : 02) 2061 - 0759   - Skype : devzone24
-  주소 : 서울특별시 양천구 목1동 923-14. 현대드림타워 1024호
-  기술 문의: 02) 2061-1259 김민석 기술이사


댓글 없음:

댓글 쓰기