String.GetHashCode 메서드

정의

오버로드

GetHashCode(ReadOnlySpan<Char>, StringComparison)

지정된 규칙을 사용하여 제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.

GetHashCode(StringComparison)

지정된 규칙을 사용하여 이 문자열의 해시 코드를 반환합니다.

GetHashCode()

해당 문자열에 대한 해시 코드를 반환합니다.

GetHashCode(ReadOnlySpan<Char>)

제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.

GetHashCode(ReadOnlySpan<Char>, StringComparison)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

지정된 규칙을 사용하여 제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.

public:
 static int GetHashCode(ReadOnlySpan<char> value, StringComparison comparisonType);
public static int GetHashCode (ReadOnlySpan<char> value, StringComparison comparisonType);
static member GetHashCode : ReadOnlySpan<char> * StringComparison -> int
Public Shared Function GetHashCode (value As ReadOnlySpan(Of Char), comparisonType As StringComparison) As Integer

매개 변수

value
ReadOnlySpan<Char>

읽기 전용 문자 범위입니다.

comparisonType
StringComparison

비교에 사용할 규칙을 지정하는 열거형 값 중 하나입니다.

반환

부호 있는 32비트 정수 해시 코드입니다.

적용 대상

GetHashCode(StringComparison)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

지정된 규칙을 사용하여 이 문자열의 해시 코드를 반환합니다.

public:
 int GetHashCode(StringComparison comparisonType);
public int GetHashCode (StringComparison comparisonType);
override this.GetHashCode : StringComparison -> int
Public Function GetHashCode (comparisonType As StringComparison) As Integer

매개 변수

comparisonType
StringComparison

비교에 사용할 규칙을 지정하는 열거형 값 중 하나입니다.

반환

부호 있는 32비트 정수 해시 코드입니다.

적용 대상

GetHashCode()

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

해당 문자열에 대한 해시 코드를 반환합니다.

public:
 override int GetHashCode();
public override int GetHashCode ();
override this.GetHashCode : unit -> int
Public Overrides Function GetHashCode () As Integer

반환

부호 있는 32비트 정수 해시 코드입니다.

예제

다음 예제에서는 다양 한 입력 문자열을 GetHashCode 사용 하 여 메서드를 보여 줍니다.

using namespace System;

void DisplayHashCode( String^ Operand )
{
   int HashCode = Operand->GetHashCode();
   Console::WriteLine( "The hash code for \"{0}\" is: 0x{1:X8}, {1}", Operand, HashCode );
}

int main()
{
   DisplayHashCode( "" );
   DisplayHashCode( "a" );
   DisplayHashCode( "ab" );
   DisplayHashCode( "abc" );
   DisplayHashCode( "abd" );
   DisplayHashCode( "abe" );
   DisplayHashCode( "abcdef" );
   DisplayHashCode( "abcdeg" );
   DisplayHashCode( "abcdeh" );
   DisplayHashCode( "abcdei" );
   DisplayHashCode( "Abcdeg" );
   DisplayHashCode( "Abcdeh" );
   DisplayHashCode( "Abcdei" );
}

/*
This example displays output like the following:
      The hash code for "" is: 0x2D2816FE, 757602046
      The hash code for "a" is: 0xCDCAB7BF, -842352705
      The hash code for "ab" is: 0xCDE8B7BF, -840386625
      The hash code for "abc" is: 0x2001D81A, 536991770
      The hash code for "abd" is: 0xC2A94CB5, -1029092171
      The hash code for "abe" is: 0x6550C150, 1699791184
      The hash code for "abcdef" is: 0x1762906D, 392335469
      The hash code for "abcdeg" is: 0x1763906D, 392401005
      The hash code for "abcdeh" is: 0x175C906D, 391942253
      The hash code for "abcdei" is: 0x175D906D, 392007789
      The hash code for "Abcdeg" is: 0x1763954D, 392402253
      The hash code for "Abcdeh" is: 0x175C954D, 391943501
      The hash code for "Abcdei" is: 0x175D954D, 392009037
*/
using System;

class GetHashCode 
{
    public static void Main() 
    {
        DisplayHashCode( "" );
        DisplayHashCode( "a" );
        DisplayHashCode( "ab" );
        DisplayHashCode( "abc" );
        DisplayHashCode( "abd" );
        DisplayHashCode( "abe" );
        DisplayHashCode( "abcdef" );
        DisplayHashCode( "abcdeg" );
        DisplayHashCode( "abcdeh" );
        DisplayHashCode( "abcdei" );
        DisplayHashCode( "Abcdeg" );
        DisplayHashCode( "Abcdeh" );
        DisplayHashCode( "Abcdei" );
    }

    static void DisplayHashCode( String Operand )
    {
        int     HashCode = Operand.GetHashCode( );
        Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}",
                          Operand, HashCode );
    }
}
/*
      This example displays output like the following:
      The hash code for "" is: 0x2D2816FE, 757602046
      The hash code for "a" is: 0xCDCAB7BF, -842352705
      The hash code for "ab" is: 0xCDE8B7BF, -840386625
      The hash code for "abc" is: 0x2001D81A, 536991770
      The hash code for "abd" is: 0xC2A94CB5, -1029092171
      The hash code for "abe" is: 0x6550C150, 1699791184
      The hash code for "abcdef" is: 0x1762906D, 392335469
      The hash code for "abcdeg" is: 0x1763906D, 392401005
      The hash code for "abcdeh" is: 0x175C906D, 391942253
      The hash code for "abcdei" is: 0x175D906D, 392007789
      The hash code for "Abcdeg" is: 0x1763954D, 392402253
      The hash code for "Abcdeh" is: 0x175C954D, 391943501
      The hash code for "Abcdei" is: 0x175D954D, 392009037
*/
let displayHashCode operand =
    let hashCode = operand.GetHashCode()
    printfn $"The hash code for \"%s{operand}\" is: 0x{1:X8}, {hashCode}"

displayHashCode ""
displayHashCode "a"
displayHashCode "ab"
displayHashCode "abc"
displayHashCode "abd"
displayHashCode "abe"
displayHashCode "abcdef"
displayHashCode "abcdeg"
displayHashCode "abcdeh"
displayHashCode "abcdei"
displayHashCode "Abcdeg"
displayHashCode "Abcdeh"
displayHashCode "Abcdei"

(*
      This example displays output like the following:
      The hash code for "" is: 0x2D2816FE, 757602046
      The hash code for "a" is: 0xCDCAB7BF, -842352705
      The hash code for "ab" is: 0xCDE8B7BF, -840386625
      The hash code for "abc" is: 0x2001D81A, 536991770
      The hash code for "abd" is: 0xC2A94CB5, -1029092171
      The hash code for "abe" is: 0x6550C150, 1699791184
      The hash code for "abcdef" is: 0x1762906D, 392335469
      The hash code for "abcdeg" is: 0x1763906D, 392401005
      The hash code for "abcdeh" is: 0x175C906D, 391942253
      The hash code for "abcdei" is: 0x175D906D, 392007789
      The hash code for "Abcdeg" is: 0x1763954D, 392402253
      The hash code for "Abcdeh" is: 0x175C954D, 391943501
      The hash code for "Abcdei" is: 0x175D954D, 392009037
*)
Module GetHashCode
    Sub Main()
        DisplayHashCode("")
        DisplayHashCode("a")
        DisplayHashCode("ab")
        DisplayHashCode("abc")
        DisplayHashCode("abd")
        DisplayHashCode("abe")
        DisplayHashCode("abcdef")
        DisplayHashCode("abcdeg")
        DisplayHashCode("abcdeh")
        DisplayHashCode("abcdei")
        DisplayHashCode("Abcdeg")
        DisplayHashCode("Abcdeh")
        DisplayHashCode("Abcdei")
    End Sub
       
    Sub DisplayHashCode(Operand As String)
        Dim HashCode As Integer = Operand.GetHashCode()
        Console.WriteLine("The hash code for ""{0}"" is: 0x{1:X8}, {1}", 
                          Operand, HashCode)
    End Sub 
End Module 
' This example displays output like the following:
'       The hash code for "" is: 0x2D2816FE, 757602046
'       The hash code for "a" is: 0xCDCAB7BF, -842352705
'       The hash code for "ab" is: 0xCDE8B7BF, -840386625
'       The hash code for "abc" is: 0x2001D81A, 536991770
'       The hash code for "abd" is: 0xC2A94CB5, -1029092171
'       The hash code for "abe" is: 0x6550C150, 1699791184
'       The hash code for "abcdef" is: 0x1762906D, 392335469
'       The hash code for "abcdeg" is: 0x1763906D, 392401005
'       The hash code for "abcdeh" is: 0x175C906D, 391942253
'       The hash code for "abcdei" is: 0x175D906D, 392007789
'       The hash code for "Abcdeg" is: 0x1763954D, 392402253
'       The hash code for "Abcdeh" is: 0x175C954D, 391943501
'       The hash code for "Abcdei" is: 0x175D954D, 392009037

설명

GetHashCode 동작은 공용 언어 런타임의 한 버전에서 다른 버전으로 변경될 수 있는 구현에 따라 달라집니다. 이 문제가 발생할 수 있는 이유는 의 GetHashCode성능을 향상시키기 위해서입니다.

중요

두 문자열 개체가 같으면 메서드는 GetHashCode 동일한 값을 반환합니다. 그러나 각 고유 문자열 값에 대한 고유 해시 코드 값은 없습니다. 다른 문자열은 동일한 해시 코드를 반환할 수 있습니다.

해시 코드 자체는 안정적이라고 보장되지 않습니다. 동일한 문자열에 대한 해시 코드는 .NET 구현, .NET 버전 및 단일 버전의 .NET 플랫폼(예: 32비트 및 64비트)에서 다를 수 있습니다. 일부 경우에도 애플리케이션 도메인 별로 다릅니다 수 있습니다. 이는 동일한 프로그램의 두 후속 실행이 서로 다른 해시 코드를 반환할 수 있음을 의미합니다.

결과적으로 코드 생성 된 애플리케이션 도메인 외부에서 사용 되지 않아야 하는 해시 컬렉션의 키 필드를 사용 하지 않아야 및 유지 되지 해야 합니다.

마지막으로 암호화된 강력한 해시가 필요한 경우 암호화 해시 함수에서 반환하는 값 대신 해시 코드를 사용하지 마세요. 암호화 해시의 경우 또는 System.Security.Cryptography.KeyedHashAlgorithm 클래스에서 파생된 클래스를 System.Security.Cryptography.HashAlgorithm 사용합니다.

해시 코드에 대한 자세한 내용은 를 참조하세요 Object.GetHashCode.

.NET Framework 데스크톱 앱에서는 UseRandomizedStringHashAlgorithm> 요소를 사용하여< 애플리케이션별 도메인 기준으로 고유한 해시 코드를 생성할 수 있습니다. 이렇게 하면 충돌 횟수를 줄이고 해시 테이블을 사용하는 삽입 및 조회의 전반적인 성능을 향상시킬 수 있습니다. 다음 예제에서는 UseRandomizedStringHashAlgorithm> 요소를 사용하는< 방법을 보여줍니다. 프라이빗 문자열 상수를 포함하는 클래스를 정의합니다 DisplayString . 이 상수 s의 값은 "문자열입니다."입니다. 또한 문자열 값과 해당 해시 코드를 표시하는 메서드와 메서드가 실행 중인 애플리케이션 도메인의 이름도 포함 ShowStringHashCode 됩니다.

using System;

public class Example
{
   public static void Main()
   {
      // Show hash code in current domain.
      DisplayString display = new DisplayString();
      display.ShowStringHashCode();
      
      // Create a new app domain and show string hash code.
      AppDomain domain = AppDomain.CreateDomain("NewDomain");
      var display2 = (DisplayString) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, 
                                                          "DisplayString");   
      display2.ShowStringHashCode();
   }
}

public class DisplayString : MarshalByRefObject
{
   private String s = "This is a string.";
   
   public override bool Equals(Object obj)
   {
      String s2 = obj as String; 
      if (s2 == null)
         return false;
      else
         return s == s2; 
   }

   public bool Equals(String str)
   {
      return s == str;
   }    
   
   public override int GetHashCode()
   {
      return s.GetHashCode();
   }
   
   public override String ToString() 
   {
      return s;
   }

   public void ShowStringHashCode()
   {
      Console.WriteLine("String '{0}' in domain '{1}': {2:X8}",
                        s, AppDomain.CurrentDomain.FriendlyName, 
                        s.GetHashCode());
   }
}
open System

type DisplayString() =
    inherit MarshalByRefObject()
    let s = "This is a string."
   
    override _.Equals(obj) =
        match obj with
        | :? string as s2 -> s = s2
        | _ -> false

    member _.Equals(str) =
        s = str
   
    override _.GetHashCode() =
        s.GetHashCode()
   
    override _.ToString() = 
        s

    member _.ShowStringHashCode() =
        printfn $"String '{s}' in domain '{AppDomain.CurrentDomain.FriendlyName}': {s.GetHashCode():X8}"

// Show hash code in current domain.
let display = DisplayString()
display.ShowStringHashCode()

// Create a new app domain and show string hash code.
let domain = AppDomain.CreateDomain "NewDomain"
let display2 = domain.CreateInstanceAndUnwrap(typeof<DisplayString>.Assembly.FullName, "DisplayString") :?> DisplayString   
display2.ShowStringHashCode()
Module Example
   Public Sub Main()
      ' Show hash code in current domain.
      Dim display As New DisplayString()
      display.ShowStringHashCode()
      
      ' Create a new app domain and show string hash code.
      Dim domain As AppDomain = AppDomain.CreateDomain("NewDomain")
      Dim display2 = CType(domain.CreateInstanceAndUnwrap(GetType(Example).Assembly.FullName, 
                                                          "DisplayString"), DisplayString)   
      display2.ShowStringHashCode()
   End Sub
End Module

Public Class DisplayString : Inherits MarshalByRefObject

   Private s As String = "This is a string."
   
   Public Overrides Function Equals(obj As Object) As Boolean
      Dim s2 As String = TryCast(obj, String)
      If s2 Is Nothing Then
         Return False
      Else
         Return s = s2 
      End If
   End Function

   Public Overloads Function Equals(str As String) As Boolean
      Return s = str
   End Function    
   
   Public Overrides Function GetHashCode() As Integer
      Return s.GetHashCode()
   End Function
   
   Public Overrides Function ToString() As String
      Return s
   End Function

   Public Sub ShowStringHashCode()
      Console.WriteLine("String '{0}' in domain '{1}': {2:X8}",
                        s, AppDomain.CurrentDomain.FriendlyName, 
                        s.GetHashCode())
   End Sub
End Class

구성 파일을 지정하지 않고 이 예제를 실행할 경우 다음과 유사한 출력이 표시됩니다. 문자열의 해시 코드는 두 애플리케이션 도메인에서 동일합니다.

String 'This is a string.' in domain 'PerDomain.exe': 941BCEAC
String 'This is a string.' in domain 'NewDomain': 941BCEAC

하지만 샘플 디렉터리에 다음의 구성을 추가하고 샘플을 실행하는 경우 동일 문자열의 해시 코드는 애플리케이션 도메인에 의해 달라집니다.

<?xml version ="1.0"?>
<configuration>
   <runtime>
      <UseRandomizedStringHashAlgorithm enabled="1" />
   </runtime>
</configuration>

구성 파일이 있는 경우 예제는 다음과 같은 출력을 표시합니다.

String 'This is a string.' in domain 'PerDomain.exe': 5435776D
String 'This is a string.' in domain 'NewDomain': 75CC8236

중요

해시 코드는 해시 테이블에서 키 지정 개체를 효율적으로 삽입하고 검색하는 데 사용됩니다. 그러나 해시 코드는 문자열을 고유하게 식별하지 않습니다. 동일한 문자열에는 동일한 해시 코드가 있지만 공용 언어 런타임은 동일한 해시 코드를 다른 문자열에 할당할 수도 있습니다. 또한, 해시 코드는.NET 버전, 단일 버전 내에서 플랫폼 및 애플리케이션 도메인 별로 달라질 수 있습니다. 따라서 해시 코드 값을 직렬화하거나 유지해서는 안 되며 해시 테이블 또는 사전에서 키로 사용해서는 안 됩니다.

해시 코드 및 GetHashCode 메서드 사용에 대한 자세한 내용은 를 참조하세요 Object.GetHashCode.

호출자 참고

에서 반환되는 GetHashCode() 값은 플랫폼에 따라 다릅니다. 32비트 및 64비트 버전의 .NET Framework 다릅니다. .NET Framework 버전과 .NET Core 버전 간에도 다를 수 있습니다.

추가 정보

적용 대상

GetHashCode(ReadOnlySpan<Char>)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.

public:
 static int GetHashCode(ReadOnlySpan<char> value);
public static int GetHashCode (ReadOnlySpan<char> value);
static member GetHashCode : ReadOnlySpan<char> -> int
Public Shared Function GetHashCode (value As ReadOnlySpan(Of Char)) As Integer

매개 변수

value
ReadOnlySpan<Char>

읽기 전용 문자 범위입니다.

반환

부호 있는 32비트 정수 해시 코드입니다.

적용 대상