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

Definição

Sobrecargas

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

Retorna o código hash desta cadeia de caracteres.Returns the hash code for this string.

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

Parâmetros

Retornos

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

Parâmetros

Retornos

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

Parâmetros

Retornos

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

Retorna o código hash desta cadeia de caracteres.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

Retornos

Um código de hash do inteiro assinado de 32 bits.A 32-bit signed integer hash code.

Exemplos

O exemplo a seguir demonstra o GetHashCode método usando várias cadeias de caracteres de entrada.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

Comentários

O comportamento de GetHashCode depende de sua implementação, o que pode ser alterado de uma versão do common language runtime para outro.The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. Um motivo por que isso pode acontecer é melhorar o desempenho de GetHashCode.A reason why this might happen is to improve the performance of GetHashCode.

Importante

Se dois objetos de cadeia de caracteres são iguais, o GetHashCode método retorna valores idênticos.If two string objects are equal, the GetHashCode method returns identical values. No entanto, não há um valor de código hash exclusivo para cada valor de cadeia de caracteres exclusiva.However, there is not a unique hash code value for each unique string value. Cadeias de caracteres diferentes podem retornar o mesmo código hash.Different strings can return the same hash code.

O código de hash em si não é garantido para ser estável.The hash code itself is not guaranteed to be stable. Códigos de hash para cadeias de caracteres idênticas podem ser diferentes entre implementações do .NET, entre as versões do .NET e entre plataformas do .NET (por exemplo, 32 bits e 64 bits) para uma única versão do .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. Em alguns casos, pode até mesmo diferem por domínio de aplicativo.In some cases, they can even differ by application domain. Isso implica que as duas execuções subsequentes do mesmo programa podem retornar códigos de hash diferente.This implies that two subsequent runs of the same program may return different hash codes.

Como resultado, hash códigos nunca devem ser usados fora do domínio de aplicativo no qual eles foram criados, eles nunca devem ser usados como campos de chave em uma coleção e nunca deve ser mantidos.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.

Por fim, não use o código de hash em vez de um valor retornado por uma função de hash criptográfica, se você precisar de um hash criptograficamente forte.Finally, don't use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. Para hashes criptográficos, use uma classe derivada de System.Security.Cryptography.HashAlgorithm ou System.Security.Cryptography.KeyedHashAlgorithm classe.For cryptographic hashes, use a class derived from the System.Security.Cryptography.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm class.

Para obter mais informações sobre códigos de hash, consulte Object.GetHashCode.For more information about hash codes, see Object.GetHashCode.

Em aplicativos da área de trabalho, você pode usar o <UseRandomizedStringHashAlgorithm > elemento para gerar códigos de hash exclusivo em uma base domínio de aplicativo.In desktop apps, you can use the <UseRandomizedStringHashAlgorithm> element to generate unique hash codes on a per application domain basis. Isso pode reduzir o número de colisões e melhorar o desempenho geral de inserções e pesquisas que usam tabelas de hash.This can reduce the number of collisions and improve the overall performance of insertions and lookups that use hash tables. O exemplo a seguir mostra como usar o <UseRandomizedStringHashAlgorithm > elemento.The following example shows how to use the <UseRandomizedStringHashAlgorithm> element. Ele define uma DisplayString classe que inclui uma constante de cadeia de caracteres privados, s, cujo valor é "Esta é uma cadeia de caracteres."It defines a DisplayString class that includes a private string constant, s, whose value is "This is a string." Também inclui um método ShowStringHashCode que exibe o valor de cadeia de caracteres e seu código de hash com o nome do domínio do aplicativo no qual o método está sendo executado.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

Quando você executa o exemplo sem fornecer um arquivo de configuração, ele exibe uma saída semelhante à seguinte.When you run the example without supplying a configuration file, it displays output similar to the following. Observe que os códigos hash para a cadeia de caracteres são idênticos nos dois domínios de aplicativo.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

Entretanto, se você adicionar o seguinte arquivo de configuração ao diretório de exemplo e, então, executar o exemplo, os códigos hash da mesma cadeia de caracteres diferirão de acordo com o domínio de aplicativo.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>

Quando o arquivo de configuração estiver presente, o exemplo exibe a saída a seguir: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

Importante

Códigos de hash são usados para inserir e recuperar objetos com chave das tabelas de hash com eficiência.Hash codes are used to insert and retrieve keyed objects from hash tables efficiently. No entanto, os códigos de hash não identificam exclusivamente as cadeias de caracteres.However, hash codes don't uniquely identify strings. Cadeias de caracteres idênticas têm códigos hash igual, mas o common language runtime também pode atribuir o mesmo código hash para cadeias de caracteres diferentes.Identical strings have equal hash codes, but the common language runtime can also assign the same hash code to different strings. Além disso, os códigos hash podem variar por versão do .NET, plataforma dentro de uma única versão e domínio do aplicativo.In addition, hash codes can vary by version of .NET, by platform within a single version, and by application domain. Por isso, você não deve serializar ou manter valores de hash de código, nem deve você usá-los como chaves em uma tabela de hash ou dicionário.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.

Para obter informações adicionais sobre o uso dos códigos de hash e o GetHashCode método, consulte Object.GetHashCode.For additional information about the use of hash codes and the GetHashCode method, see Object.GetHashCode.

Notas aos Chamadores

O valor retornado por GetHashCode() é dependente de plataforma.The value returned by GetHashCode() is platform-dependent. Ele é diferente nas versões de 32 bits e 64 bits do .NET Framework.It differs on the 32-bit and 64-bit versions of the .NET Framework. Ele também pode ser diferente entre as versões do .NET Framework e .NET Core.It also can differ between versions of the .NET Framework and .NET Core.

Veja também

Aplica-se a