String.GetHashCode String.GetHashCode String.GetHashCode String.GetHashCode Method

定義

多載

GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison)

使用指定的規則,傳回所提供唯讀字元範圍的雜湊碼。Returns the hash code for the provided read-only character span using the specified rules.

GetHashCode(StringComparison) GetHashCode(StringComparison) GetHashCode(StringComparison) GetHashCode(StringComparison)

使用指定規則傳回這個字串的雜湊碼。Returns the hash code for this string using the specified rules.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

傳回這個字串的雜湊碼。Returns the hash code for this string.

GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>)

傳回所提供唯讀字元範圍的雜湊碼。Returns the hash code for the provided read-only character span.

GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison) 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 StringComparison StringComparison 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) GetHashCode(StringComparison) GetHashCode(StringComparison) 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 StringComparison StringComparison StringComparison

其中一個列舉值,指定要用於比較的規則。One of the enumeration values that specifies the rules to use in the comparison.

傳回

32 位元帶正負號的整數雜湊碼。A 32-bit signed integer hash code.

GetHashCode() GetHashCode() GetHashCode() 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取決於其執行,這可能會從 common language runtime 的某個版本變更為另一個版本。The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. 可能發生這種情況的原因是要改善的效能GetHashCodeA reason why this might happen is to improve the performance of GetHashCode.

重要

如果兩個字串物件相等,則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 平臺(例如32位和64位)之間,適用于 .net 的單一版本可能會不同。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.HashAlgorithmSystem.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一個類別,其中包含私用字串s常數,其值為 "This is a string"。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.GetHashCodeFor 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 Framework 和 .NET Core 的版本也可能不同。It also can differ between versions of the .NET Framework and .NET Core.

另請參閱

GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>) 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.

適用於