String.GetHashCode 方法

定義

多載

GetHashCode(ReadOnlySpan<Char>, StringComparison)

使用指定的規則,傳回所提供唯讀字元範圍的雜湊碼。

GetHashCode(StringComparison)

使用指定規則傳回這個字串的雜湊碼。

GetHashCode()

傳回這個字串的雜湊碼。

GetHashCode(ReadOnlySpan<Char>)

傳回所提供唯讀字元範圍的雜湊碼。

GetHashCode(ReadOnlySpan<Char>, StringComparison)

使用指定的規則,傳回所提供唯讀字元範圍的雜湊碼。

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)

使用指定規則傳回這個字串的雜湊碼。

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()

傳回這個字串的雜湊碼。

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 取決於其實作,這可能會從一個版本的 Common Language Runtime 變更為另一個版本。 發生此情況的原因,是改善 的 GetHashCode 效能。

重要

如果兩個字串物件相等,此方法會 GetHashCode 傳回相同的值。 不過,每個唯一字串值都沒有唯一的雜湊碼值。 不同的字串可以傳回相同的雜湊碼。

雜湊程式碼本身不保證穩定。 相同字串的雜湊碼在 .NET 實作、.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

重要

雜湊碼可用來有效率地從雜湊表插入和擷取索引鍵物件。 不過,雜湊碼不會唯一識別字串。 相同的字串具有相同的雜湊碼,但 Common Language Runtime 也可以將相同的雜湊程式碼指派給不同的字串。 此外,雜湊碼可能會因 .NET 版本、平臺在單一版本和應用程式域內而有所不同。 因此,您不應該序列化或保存雜湊碼值,也不應該將它們當做雜湊表或字典中的索引鍵使用。

如需使用雜湊碼和 GetHashCode 方法的其他資訊,請參閱 Object.GetHashCode

給呼叫者的注意事項

GetHashCode() 回的值與平臺相關。 它與 32 位和 64 位版本的 .NET Framework 不同。 它也可以在 .NET Framework 和 .NET Core 的版本之間有所差異。

另請參閱

適用於

GetHashCode(ReadOnlySpan<Char>)

傳回所提供唯讀字元範圍的雜湊碼。

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 位元帶正負號的整數雜湊碼。

適用於