String.GetHashCode 메서드
정의
오버로드
GetHashCode(ReadOnlySpan<Char>, StringComparison) |
지정된 규칙을 사용하여 제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.Returns the hash code for the provided read-only character span using the specified rules. |
GetHashCode(StringComparison) |
지정된 규칙을 사용하여 이 문자열의 해시 코드를 반환합니다.Returns the hash code for this string using the specified rules. |
GetHashCode() |
해당 문자열에 대한 해시 코드를 반환합니다.Returns the hash code for this string. |
GetHashCode(ReadOnlySpan<Char>) |
제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.Returns the hash code for the provided read-only character span. |
GetHashCode(ReadOnlySpan<Char>, StringComparison)
지정된 규칙을 사용하여 제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.Returns the hash code for the provided read-only character span using the specified rules.
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>
읽기 전용 문자 범위입니다.A read-only character span.
- comparisonType
- StringComparison
비교에 사용할 규칙을 지정하는 열거형 값 중 하나입니다.One of the enumeration values that specifies the rules to use in the comparison.
반환
부호 있는 32비트 정수 해시 코드입니다.A 32-bit signed integer hash code.
GetHashCode(StringComparison)
지정된 규칙을 사용하여 이 문자열의 해시 코드를 반환합니다.Returns the hash code for this string using the specified rules.
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
비교에 사용할 규칙을 지정하는 열거형 값 중 하나입니다.One of the enumeration values that specifies the rules to use in the comparison.
반환
부호 있는 32비트 정수 해시 코드입니다.A 32-bit signed integer hash code.
GetHashCode()
해당 문자열에 대한 해시 코드를 반환합니다.Returns the hash code for this string.
public:
override int GetHashCode();
public override int GetHashCode ();
override this.GetHashCode : unit -> int
Public Overrides Function GetHashCode () As Integer
반환
부호 있는 32비트 정수 해시 코드입니다.A 32-bit signed integer hash code.
예제
다음 예제는 GetHashCode 다양 한를 사용 하 여 메서드 입력 문자열입니다.The following example demonstrates the GetHashCode method using various input strings.
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
*/
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 다른 공용 언어 런타임의 버전 간에 변경 될 수 있는 해당 구현에 따라 달라 집니다.The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. 이 문제가 발생 하는 이유는 성능을 개선 하기 위해 GetHashCode합니다.A reason why this might happen is to improve the performance of GetHashCode.
중요
두 string 개체 같으면는 GetHashCode 메서드 같은 값을 반환 합니다.If two string objects are equal, the GetHashCode method returns identical values. 그러나 각 고유한 문자열 값에 대 한 고유 해시 코드 값 하지입니다.However, there is not a unique hash code value for each unique string value. 다른 문자열에는 같은 해시 코드를 반환할 수 있습니다.Different strings can return the same hash code.
자체 해시 코드를 안정적인 것으로 보장 되지 않습니다.The hash code itself is not guaranteed to be stable. 동일한 문자열에 대 한 해시 코드는.NET 구현에서.NET 버전 간에 및 단일 버전의.NET에 대 한.NET 플랫폼 (예: 32 비트 및 64 비트) 간에 달라질 수 있습니다.Hash codes for identical strings can differ across .NET implementations, across .NET versions, and across .NET platforms (such as 32-bit and 64-bit) for a single version of .NET. 일부 경우에도 응용 프로그램 도메인 별로 다릅니다 수 있습니다.In some cases, they can even differ by application domain. 즉, 동일한 프로그램의 후속 실행을 두는 서로 다른 해시 코드를 반환할 수 있습니다.This implies that two subsequent runs of the same program may return different hash codes.
결과적으로 코드 생성 된 애플리케이션 도메인 외부에서 사용 되지 않아야 하는 해시 컬렉션의 키 필드를 사용 하지 않아야 및 유지 되지 해야 합니다.As a result, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection, and they should never be persisted.
마지막으로 없는 암호화 된 강력한 해시 해야 하는 경우 암호화 해시 함수에서 반환 된 값 대신 해시 코드를 사용 합니다.Finally, don't use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. 암호화 해시, 파생 클래스를 사용 합니다 System.Security.Cryptography.HashAlgorithm 또는 System.Security.Cryptography.KeyedHashAlgorithm 클래스입니다.For cryptographic hashes, use a class derived from the System.Security.Cryptography.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm class.
해시 코드에 대 한 자세한 내용은 참조 하세요. Object.GetHashCode합니다.For more information about hash codes, see Object.GetHashCode.
데스크톱 앱에서는 <UseRandomizedStringHashAlgorithm > 요소 를 사용 하 여 응용 프로그램 도메인 별로 고유한 해시 코드를 생성할 수 있습니다.In desktop apps, you can use the <UseRandomizedStringHashAlgorithm> element to generate unique hash codes on a per application domain basis. 이 충돌을 줄이려면 하 고 삽입 및 해시 테이블을 사용 하는 조회의 전반적인 성능을 향상 시킬 수 있습니다.This can reduce the number of collisions and improve the overall performance of insertions and lookups that use hash tables. 다음 예제에서는 <UseRandomizedStringHashAlgorithm > 요소를 사용 하는 방법을 보여 줍니다.The following example shows how to use the <UseRandomizedStringHashAlgorithm> element. 정의 된 DisplayString
private 문자열 상수를 포함 하는 클래스 s
, 값인 "는 문자열입니다."It defines a DisplayString
class that includes a private string constant, s
, whose value is "This is a string." 메서드를 실행하는 애플리케이션 도메인의 이름과 함께 문자열 값 및 해시 코드를 표시하는 ShowStringHashCode
메서드도 포함합니다.It also includes a ShowStringHashCode
method that displays the string value and its hash code along with the name of the application domain in which the method is executing.
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());
}
}
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
구성 파일을 제공 하지 않고 예제를 실행 하면 다음과 유사한 출력이 표시 됩니다.When you run the example without supplying a configuration file, it displays output similar to the following. 문자열의 해시 코드는 두 애플리케이션 도메인에서 동일합니다.Note that the hash codes for the string are identical in the two application domains.
String 'This is a string.' in domain 'PerDomain.exe': 941BCEAC
String 'This is a string.' in domain 'NewDomain': 941BCEAC
하지만 샘플 디렉터리에 다음의 구성을 추가하고 샘플을 실행하는 경우 동일 문자열의 해시 코드는 애플리케이션 도메인에 의해 달라집니다.However, if you add the following configuration file to the example's directory and then run the example, the hash codes for the same string will differ by application domain.
<?xml version ="1.0"?>
<configuration>
<runtime>
<UseRandomizedStringHashAlgorithm enabled="1" />
</runtime>
</configuration>
구성 파일에 있는 경우이 예제에서는 다음과 같은 출력이 표시 됩니다.When the configuration file is present, the example displays the following output:
String 'This is a string.' in domain 'PerDomain.exe': 5435776D
String 'This is a string.' in domain 'NewDomain': 75CC8236
중요
해시 코드는 삽입 및 해시 테이블에서 키가 지정 된 개체를 효율적으로 검색에 사용 됩니다.Hash codes are used to insert and retrieve keyed objects from hash tables efficiently. 그러나 해시 코드 문자열을 고유 하 게 식별 하지 않습니다.However, hash codes don't uniquely identify strings. 동일한 문자열은 같은 해시 코드를 갖지만 공용 언어 런타임에서 다른 문자열에는 같은 해시 코드를 할당할 수도 있습니다.Identical strings have equal hash codes, but the common language runtime can also assign the same hash code to different strings. 또한, 해시 코드는.NET 버전, 단일 버전 내에서 플랫폼 및 애플리케이션 도메인 별로 달라질 수 있습니다.In addition, hash codes can vary by version of .NET, by platform within a single version, and by application domain. 이 인해 직렬화 또는 해시 코드 값을 유지 해야 하거나 해시 테이블 또는 사전에서 키로 사용 합니다.Because of this, you should not serialize or persist hash code values, nor should you use them as keys in a hash table or dictionary.
해시 코드를 사용 하는 방법에 대 한 자세한 내용은 하며 GetHashCode
메서드를 참조 하세요 Object.GetHashCode합니다.For additional information about the use of hash codes and the GetHashCode
method, see Object.GetHashCode.
호출자 참고
반환한 값 GetHashCode() 은 플랫폼에 따라 다릅니다.The value returned by GetHashCode() is platform-dependent. 32 비트 및 64 비트 버전의.NET Framework에서 달라 집니다.It differs on the 32-bit and 64-bit versions of the .NET Framework. .NET Core와.NET Framework의 버전 간에 달라질 수 있습니다 것입니다.It also can differ between versions of the .NET Framework and .NET Core.
추가 정보
GetHashCode(ReadOnlySpan<Char>)
제공된 읽기 전용 문자 범위의 해시 코드를 반환합니다.Returns the hash code for the provided read-only character span.
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>
읽기 전용 문자 범위입니다.A read-only character span.
반환
부호 있는 32비트 정수 해시 코드입니다.A 32-bit signed integer hash code.