Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.

GetHashCode 코드 질문이 종종 올라오니,

GethashCode와 String대한 질문
; https://www.sysnet.pe.kr/3/0/5514

GetHashCode 질문있습니다!
; https://www.sysnet.pe.kr/3/0/5480

간단하게 팁 정도로 공유해서 전달해 드리는 것이 좋을 듯해서 글을 써봅니다. ^^

보통, 닷넷에서 GetHashCode 메서드를 이용해 hash 값을 구하긴 해도 막상 우리가 만든 타입에서 GetHashCode를 작성하려고 하면 코드 구현에서 고민이 됩니다. 가령 다음과 같은 예제가 있을 때,

public class Person
{
    public string Name;
    public int Age;

    public override int GetHashCode()
    {
        // ... hashcode 계산 ...
    }
}

과연 저 값을 어떻게 계산해야 할지 고민이 될 것입니다. 이럴 때는, 그냥 마이크로소프트가 하는 방법을 따르는 것도 좋습니다. 이를 위해 동일한 타입을 C# 9.0의 record로,

C# 9.0 - (9) 레코드(Records)
; https://www.sysnet.pe.kr/2/0/12392

만들면,

public record Person2
{
    public string Name;
    public int Age;
}

빌드 결과물로부터 역어셈블러를 통해 다음의 결과를 얻을 수 있습니다.

public override int GetHashCode()
{
    return (EqualityComparer<Type>.Default.GetHashCode(this.EqualityContract) * -1521134295
     + EqualityComparer<string>.Default.GetHashCode(this.Name)) * -1521134295
     + EqualityComparer<int>.Default.GetHashCode(this.Age);
}

음... 별다른 양심의 거리낌 없이 ^^ 복사해서 쓰면 됩니다. 만약 컬렉션 내에 같은 타입끼리만 있다면 다음과 같은 식으로 간략화해 처리해도 무방합니다.

public class Person
{
    public string Name;
    public int Age;

    public override int GetHashCode()
    {
        return EqualityComparer<string>.Default.GetHashCode(this.Name)) * -1521134295
             + EqualityComparer<int>.Default.GetHashCode(this.Age);
    }
}

혹은 이렇게 단순화해도 좋을 듯 싶고.

public override int GetHashCode()
{
    return this.Name.GetHashCode() * -1521134295
            + this.Age.GetHashCode();
}




또는, Visual Studio를 사용하신다면 우 클릭을 해 "Quick Actions and Refactorings..." 메뉴를 불러,

cs_gethascode_1.png

선택하면 다음과 같이 "Generate Equals and GetHashCode..." 기능을 선택할 수 있습니다.

cs_gethascode_2.png

그럼 hash 값을 구할 멤버를 선택하는 대화창이 뜨고,

cs_gethascode_3.png

적절한 설정 후 "OK" 버튼을 누르면 다음과 같이 알아서 GetHashCode를 만들어 줍니다.

// .NET Core 프로젝트

public class Person
{
    public string Name;
    public int Age;

    public override bool Equals(object obj)
    {
        return obj is Person person &&
               Name == person.Name &&
               Age == person.Age;
    }

    public override int GetHashCode()
    {
        // GetHashCode() in .NET Core
        // https://bartwullems.blogspot.com/2024/01/gethashcode-in-net-core.html
        return HashCode.Combine(Name, Age);
    }

    /* 또는, https://montemagno.com/optimizing-c-struct-equality-with-iequatable/

    public bool Equals(Person other) => (Name, Age) == (other.Name, other.Age);

    public override int GetHashCode() => (Name, Age).GetHashCode();
    */
}

.NET Core 프로젝트부터 HashCode.Combine이 사용되며 .NET Framework 프로젝트에서는 다음과 같이 record에서와 유사한 코드가 생성됩니다.

// .NET Framework 프로젝트

public class Person
{
    public string Name;
    public int Age;

    public override bool Equals(object obj)
    {
        return obj is Person person &&
               Name == person.Name &&
               Age == person.Age;
    }

    public override int GetHashCode()
    {
        int hashCode = -1360180430;
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
        hashCode = hashCode * -1521134295 + Age.GetHashCode();
        return hashCode;
    }
}




다시 한번 말씀드리면, 어차피 4바이트 정숫값으로는 충돌을 피할 수 없으므로 GetHashCode에 많은 고민을 하실 필요는 없습니다. 단지, 충돌에 대비해 Equals만 제대로 정의하면 BCL 자료 구조 내에서의 동작에는 문제가 없습니다.

물론, 성능에 아주/엄청나게 민감한 응용 프로그램이라면 최대한 저 메서드를 능력껏 간소화시키시면 됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/2/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12117정성태1/15/202010849디버깅 기술: 159. C# - 디버깅 중인 프로세스를 강제로 다른 디버거에서 연결하는 방법파일 다운로드1
12116정성태1/15/202011322디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202011082디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202012944디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202013570오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/202010110오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202013403디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202011990디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209889오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209952오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010882.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012379VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010968디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011644DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202014403DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
12102정성태1/6/202011970디버깅 기술: 152. User 권한(Ring 3)의 프로그램에서 _ETHREAD 주소(및 커널 메모리를 읽을 수 있다면 _EPROCESS 주소) 구하는 방법
12101정성태1/5/202011312.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/20209329.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011656디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202011234.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209801디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911762디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201913196VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201911374.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911445.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910900디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...