共用方式為


String.GetHashCode 方法

定義

多載

名稱 Description
GetHashCode(ReadOnlySpan<Char>, StringComparison)

會依照指定規則回傳該只讀字元區間的雜湊碼。

GetHashCode(StringComparison)

會依照指定規則回傳此字串的雜湊碼。

GetHashCode()

回傳此字串的雜湊碼。

GetHashCode(ReadOnlySpan<Char>)

回傳所提供唯讀字元區間的雜湊碼。

GetHashCode(ReadOnlySpan<Char>, StringComparison)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
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)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
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()

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
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 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.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm 類別衍生的類別。

欲了解更多雜湊碼相關資訊,請參見 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>)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
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 位元有號整數雜湊碼。

適用於