1. 상황 :
클래스 정의시에
HashTable -
Dictionary
-
SortDictionary
-
SortList
-
HybredDictionary
-
IEqualityComparer 를 구현하는 형식
4. 문제 해결 쟁점
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 forGetHashCode()
- if the
GetHashCode()
is equal, it is not necessary for them to be the same; this is a collision, andEquals
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를 반환하도록 재정의해야 합니다.
- 대표 전화 : 02) 2061 - 0753 - Fax : 02) 2061 - 0759 - Skype : devzone24
- 주소 : 서울특별시 양천구 목1동 923-14. 현대드림타워 1024호
- 기술 문의: 02) 2061-1259 김민석 기술이사
댓글 없음:
댓글 쓰기