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 平台 ((例如单个版本的 .NET 的 32 位和 64 位) )而异。 在某些情况下,它们甚至可能因应用程序域而异。 这意味着同一程序的两次后续运行可能会返回不同的哈希代码。

因此,不应在创建哈希代码的应用程序域之外使用哈希代码,也不应将其用作集合中的键字段,也不应持久保存它们。

最后,如果需要加密强哈希,请不要使用哈希代码而不是加密哈希函数返回的值。 对于加密哈希,请使用派生自 或 System.Security.Cryptography.KeyedHashAlgorithm 类的System.Security.Cryptography.HashAlgorithm类。

有关哈希代码的详细信息,请参阅 Object.GetHashCode

在.NET Framework桌面应用中,可以使用 <UseRandomizedStringHashAlgorithm> 元素基于每个应用程序域生成唯一哈希代码。 这可以减少冲突的数量,并提高使用哈希表的插入和查找的总体性能。 以下示例演示如何使用 <UseRandomizedStringHashAlgorithm> 元素。 它定义一个 DisplayString 类, s其中包含一个私有字符串常量 ,其值为“This is a string”。它还包括一个 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 位有符号整数哈希代码。

适用于