C#의 Uri.GetHashCode() 메서드는 해당 URI(Uniform Resource Identifier)에 대한 해시 코드를 반환합니다. 해시 코드는 해시 테이블이나 딕셔너리 같은 컬렉션에서 객체를 빠르게 비교하거나 검색할 때 활용되는 정수 값으로, 동일한 URI는 항상 동일한 해시 코드를 갖습니다.
구문
Uri.GetHashCode() 메서드의 기본 구문은 다음과 같습니다.
public override int GetHashCode ();
이 메서드는 매개변수를 받지 않으며, int 형식의 32비트 부호 있는 정수 해시 코드를 반환합니다.
예제 1
아래 예제를 통해 Uri.GetHashCode() 메서드의 실제 사용 방법을 살펴보겠습니다.
using System;
public class Demo {
public static void Main(){
string URI1 = "https://www.tutorialspoint.com/index.htm";
Console.WriteLine("URI = "+URI1);
string URI2 = "https://www.tutorialspoint.com/";
Console.WriteLine("URI = "+URI2);
Console.WriteLine("Escaped string (URI1) = "+Uri.EscapeDataString(URI1));
Console.WriteLine("Escaped string (URI2) = "+Uri.EscapeDataString(URI2));
Console.WriteLine("GetHashCode() for URI1 = "+URI1.GetHashCode());
Console.WriteLine("GetHashCode() for URI2 = "+URI2.GetHashCode());
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
URI = https://www.tutorialspoint.com/index.htm URI = https://www.tutorialspoint.com/ Escaped string (URI1) = https%3A%2F%2Fwww.tutorialspoint.com%2Findex.htm Escaped string (URI2) = https%3A%2F%2Fwww.tutorialspoint.com%2F GetHashCode() for URI1 = -799747664 GetHashCode() for URI2 = 211597894
예제 2
이번에는 다른 URI를 사용하여 Uri.GetHashCode() 메서드를 다시 한번 살펴보겠습니다.
using System;
public class Demo {
public static void Main(){
string URI1 = "https://www.qries.com/index.htm";
Console.WriteLine("URI = "+URI1);
string URI2 = "https://www.qries.com/";
Console.WriteLine("URI = "+URI2);
Console.WriteLine("Escaped string (URI1) = "+Uri.EscapeDataString(URI1));
Console.WriteLine("Escaped string (URI2) = "+Uri.EscapeDataString(URI2));
Console.WriteLine("GetHashCode() for URI1 = "+URI1.GetHashCode());
Console.WriteLine("GetHashCode() for URI2 = "+URI2.GetHashCode());
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
URI = https://www.qries.com/index.htm URI = https://www.qries.com/ Escaped string (URI1) = https%3A%2F%2Fwww.qries.com%2Findex.htm Escaped string (URI2) = https%3A%2F%2Fwww.qries.com%2F GetHashCode() for URI1 = -39330946 GetHashCode() for URI2 = -262746624
참고 사항
해시 코드 값은 .NET 런타임 버전, 플랫폼 또는 실행 세션에 따라 달라질 수 있습니다. 따라서 해시 코드를 파일이나 데이터베이스에 영구적으로 저장하거나 애플리케이션 도메인 간에 공유하는 것은 피해야 합니다. 또한 서로 다른 URI가 우연히 같은 해시 코드를 가질 수 있으므로, 두 객체의 동등성을 판단할 때는 반드시 Equals() 메서드와 함께 사용해야 합니다.