Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Type.GetHashCode() 메서드 – 인스턴스의 해시 코드 반환하기

C#의 Type.GetHashCode() 메서드는 현재 인스턴스에 대한 해시 코드(hash code)를 반환하는 데 사용됩니다. 이 메서드는 객체를 해시 기반 컬렉션(예: Dictionary, HashSet)에서 효율적으로 조회할 수 있도록 정수 형태의 고유 식별 값을 제공합니다.

구문

기본 문법은 다음과 같습니다.

public override int GetHashCode();

매개변수는 받지 않으며, 해당 인스턴스의 해시 코드를 나타내는 int 값을 반환합니다.

예제 1: 배열 타입의 해시 코드 구하기

다음은 Type.GetHashCode() 메서드를 활용한 첫 번째 예제입니다. 문자열 배열의 타입 정보와 함께 해시 코드를 출력해 보겠습니다.

using System;
public class Demo {
    public static void Main(){
        string[] arr = {"tom", "amit", "kevin", "katie"};
        Type t1 = arr.GetType();
        Type t2 = t1.GetElementType();
        Console.WriteLine("Type = "+t2.ToString());
        Console.WriteLine("Hash Code = "+t1.GetHashCode());
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Type = System.String
Hash Code = 9144789

배열 요소의 타입은 System.String으로 확인되며, 배열 타입 인스턴스(t1)의 해시 코드가 정수로 반환된 것을 볼 수 있습니다.

예제 2: 열거형(Enum) 타입과 함께 사용하기

두 번째 예제에서는 열거형 타입에 대해 GetHashCode() 메서드를 적용하고, GetEnumNames(), GetEnumUnderlyingType(), GetEnumValues() 등 관련 메서드들도 함께 살펴봅니다.

using System;
public class Demo {
    enum Vehicle {Car, Bus, Bike, Airplane}
    public static void Main(){
        try {
            Vehicle v = Vehicle.Bike;
            Type type = v.GetType();
            Console.WriteLine("Hash code = "+type.GetHashCode());
            string[] str = type.GetEnumNames();
            Console.WriteLine("GetEnumName() to return the constant name = " + str);
            Type type2 = type.GetEnumUnderlyingType();
            Console.Write("Enum Underlying type = "+type2);
            Array arrObj = type.GetEnumValues();
            Console.Write("Values = "+arrObj);
            Console.WriteLine("\nListing constants ..");
            for (int i = 0; i < str.Length; i++)
                Console.Write("{0} ", str[i]);
        }
        catch (ArgumentException e){
            Console.WriteLine("Not an enum!");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Hash code = 44757566
GetEnumName() to return the constant name = System.String[]
Enum Underlying type = System.Int32Values = Demo+Vehicle[]
Listing constants ..
Car Bus Bike Airplane

정리

Type.GetHashCode() 메서드는 리플렉션을 통해 얻은 타입 정보를 기반으로 해시 코드를 제공하므로, 타입 비교나 해시 컬렉션에서의 키 활용 등 다양한 상황에서 유용하게 쓰일 수 있습니다. 단, 해시 코드 값은 실행 환경이나 세션마다 달라질 수 있으므로 영구 저장 용도로는 사용하지 않는 것이 좋습니다.