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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  [39]  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12664정성태6/9/20217768오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
12663정성태6/9/20219316.NET Framework: 1065. Windows Forms - 속성 창의 디자인 설정 지원: 문자열 목록 내에서 항목을 선택하는 TypeConverter 제작파일 다운로드1
12662정성태6/8/20218404.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법파일 다운로드1
12661정성태6/4/202119082.NET Framework: 1063. C# - MQTT를 이용한 클라이언트/서버(Broker) 통신 예제 [4]파일 다운로드1
12660정성태6/3/202110160.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법 [1]파일 다운로드1
12659정성태6/2/202111395Linux: 40. 우분투 설치 후 MBR 디스크 드라이브 여유 공간이 인식되지 않은 경우 - Logical Volume Management
12658정성태6/2/20218851Windows: 194. Microsoft Store에 있는 구글의 공식 Youtube App
12657정성태6/2/202110107Windows: 193. 윈도우 패키지 관리자 - winget 설치
12656정성태6/1/20218349.NET Framework: 1061. 서버 유형의 COM+에 적용할 수 없는 Server GC
12655정성태6/1/20217803오류 유형: 722. windbg/sos - savemodule - Fail to read memory
12654정성태5/31/20217835오류 유형: 721. Hyper-V - Saved 상태의 VM을 시작 시 오류 발생
12653정성태5/31/202110525.NET Framework: 1060. 닷넷 GC에 새롭게 구현되는 DPAD(Dynamic Promotion And Demotion for GC)
12652정성태5/31/20218653VS.NET IDE: 164. Visual Studio - Web Deploy로 Publish 시 암호창이 매번 뜨는 문제
12651정성태5/31/20218904오류 유형: 720. PostgreSQL - ERROR: 22P02: malformed array literal: "..."
12650정성태5/17/20218226기타: 82. OpenTabletDriver의 버튼에 더블 클릭을 매핑 및 게임에서의 지원 방법
12649정성태5/16/20219550.NET Framework: 1059. 세대 별 GC(Garbage Collection) 방식에서 Card table의 사용 의미 [1]
12648정성태5/16/20218189사물인터넷: 66. PC -> FTDI -> NodeMCU v1 ESP8266 기기를 UART 핀을 연결해 직렬 통신하는 방법파일 다운로드1
12647정성태5/15/20219433.NET Framework: 1058. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용파일 다운로드1
12646정성태5/15/20218568사물인터넷: 65. C# - Arduino IDE의 Serial Monitor 기능 구현파일 다운로드1
12645정성태5/14/20218256사물인터넷: 64. NodeMCU v1 ESP8266 - LittleFS를 이용한 와이파이 접속 정보 업데이트파일 다운로드1
12644정성태5/14/20219429오류 유형: 719. 윈도우 - 제어판의 "프로그램 및 기능" / "Windows 기능 켜기/끄기" 오류 0x800736B3
12643정성태5/14/20218620오류 유형: 718. 서버 유형의 COM+ 사용 시 0x80080005(Server execution failed) 오류 발생
12642정성태5/14/20219543오류 유형: 717. The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
12641정성태5/13/20219246디버깅 기술: 179. 윈도우용 .NET Core 3 이상에서 Windbg의 sos 사용법
12640정성태5/13/202112183오류 유형: 716. RDP 연결 - Because of a protocol error (code: 0x112f), the remote session will be disconnected. [1]
12639정성태5/12/20219086오류 유형: 715. Arduino: Open Serial Monitor - The module '...\detection.node' was compiled against a different Node.js version using NODE_MODULE_VERSION
... 31  32  33  34  35  36  37  38  [39]  40  41  42  43  44  45  ...