String.GetHashCode Metodo

Definizione

Overload

GetHashCode(ReadOnlySpan<Char>, StringComparison)

Restituisce il codice hash per l'intervallo di caratteri di sola lettura specificato usando le regole specificate.

GetHashCode(StringComparison)

Restituisce il codice hash per questa stringa usando le regole specificate.

GetHashCode()

Restituisce il codice hash di questa stringa.

GetHashCode(ReadOnlySpan<Char>)

Restituisce il codice hash per l'intervallo di caratteri di sola lettura specificato.

GetHashCode(ReadOnlySpan<Char>, StringComparison)

Restituisce il codice hash per l'intervallo di caratteri di sola lettura specificato usando le regole specificate.

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

Parametri

value
ReadOnlySpan<Char>

Intervallo di caratteri di sola lettura.

comparisonType
StringComparison

Uno dei valori di enumerazione che specifica le regole da usare per il confronto.

Restituisce

Codice hash di un intero con segno a 32 bit.

Si applica a

GetHashCode(StringComparison)

Restituisce il codice hash per questa stringa usando le regole specificate.

public:
 int GetHashCode(StringComparison comparisonType);
public int GetHashCode (StringComparison comparisonType);
override this.GetHashCode : StringComparison -> int
Public Function GetHashCode (comparisonType As StringComparison) As Integer

Parametri

comparisonType
StringComparison

Uno dei valori di enumerazione che specifica le regole da usare per il confronto.

Restituisce

Codice hash di un intero con segno a 32 bit.

Si applica a

GetHashCode()

Restituisce il codice hash di questa stringa.

public:
 override int GetHashCode();
public override int GetHashCode ();
override this.GetHashCode : unit -> int
Public Overrides Function GetHashCode () As Integer

Restituisce

Codice hash di un intero con segno a 32 bit.

Esempio

Nell'esempio seguente viene illustrato il GetHashCode metodo usando varie stringhe di input.

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

Commenti

Il comportamento di GetHashCode dipende dall'implementazione, che può cambiare da una versione di Common Language Runtime a un'altra. Un motivo per cui ciò potrebbe verificarsi è migliorare le prestazioni di GetHashCode.

Importante

Se due oggetti stringa sono uguali, il GetHashCode metodo restituisce valori identici. Non esiste tuttavia un valore di codice hash univoco per ogni valore stringa univoco. Stringhe diverse possono restituire lo stesso codice hash.

Il codice hash stesso non è garantito che sia stabile. I codici hash per stringhe identiche possono essere diversi tra le implementazioni di .NET, tra le versioni di .NET e tra le piattaforme .NET (ad esempio 32 bit e 64 bit) per una singola versione di .NET. In alcuni casi, possono anche differire in base al dominio applicazione. Ciò implica che due esecuzioni successive dello stesso programma possono restituire codici hash diversi.

Di conseguenza, i codici hash non devono mai essere usati all'esterno del dominio applicazione in cui sono stati creati, non devono mai essere usati come campi chiave in una raccolta e non devono mai essere salvati in modo permanente.

Infine, non usare il codice hash anziché un valore restituito da una funzione di hashing crittografico se è necessario un hash crittografico sicuro. Per gli hash crittografici, usare una classe derivata dalla System.Security.Cryptography.HashAlgorithm classe o System.Security.Cryptography.KeyedHashAlgorithm .

Per altre informazioni sui codici hash, vedere Object.GetHashCode.

Nelle app desktop .NET Framework è possibile usare l'elemento< UseRandomizedStringHashAlgorithm> per generare codici hash univoci per ogni dominio applicazione. In questo modo è possibile ridurre il numero di collisioni e migliorare le prestazioni complessive degli inserimenti e delle ricerche che usano tabelle hash. Nell'esempio seguente viene illustrato come usare l'elemento< UseRandomizedStringHashAlgorithm>. Definisce una DisplayString classe che include una costante stringa privata, s, il cui valore è "This is a string". Include anche un ShowStringHashCode metodo che visualizza il valore stringa e il relativo codice hash insieme al nome del dominio applicazione in cui viene eseguito il metodo.

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

Quando si esegue l'esempio senza fornire un file di configurazione, restituisce un output analogo al seguente. Si noti che i codici hash per la stringa sono identici nei due domini applicazione.

String 'This is a string.' in domain 'PerDomain.exe': 941BCEAC
String 'This is a string.' in domain 'NewDomain': 941BCEAC

Tuttavia, se si aggiunge il file di configurazione seguente alla directory di esempio e, successivamente, si esegue l'esempio, i codici hash per la stessa stringa risulteranno diversi dal dominio dell'applicazione.

<?xml version ="1.0"?>
<configuration>
   <runtime>
      <UseRandomizedStringHashAlgorithm enabled="1" />
   </runtime>
</configuration>

Quando il file di configurazione è presente, l'esempio visualizza il seguente output:

String 'This is a string.' in domain 'PerDomain.exe': 5435776D
String 'This is a string.' in domain 'NewDomain': 75CC8236

Importante

I codici hash vengono usati per inserire e recuperare in modo efficiente oggetti con chiave dalle tabelle hash. Tuttavia, i codici hash non identificano in modo univoco le stringhe. Le stringhe identiche hanno codici hash uguali, ma Common Language Runtime può anche assegnare lo stesso codice hash a stringhe diverse. Inoltre, i codici hash possono variare in base alla versione di .NET, alla piattaforma all'interno di una singola versione e al dominio dell'applicazione. Per questo motivo, non è consigliabile serializzare o rendere persistenti i valori del codice hash, né usarli come chiavi in una tabella hash o in un dizionario.

Per altre informazioni sull'uso dei codici hash e del GetHashCode metodo , vedere Object.GetHashCode.

Note per i chiamanti

Il valore restituito da GetHashCode() è dipendente dalla piattaforma. Si differenzia per le versioni a 32 bit e a 64 bit di .NET Framework. Può anche differire tra le versioni di .NET Framework e .NET Core.

Vedi anche

Si applica a

GetHashCode(ReadOnlySpan<Char>)

Restituisce il codice hash per l'intervallo di caratteri di sola lettura specificato.

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

Parametri

value
ReadOnlySpan<Char>

Intervallo di caratteri di sola lettura.

Restituisce

Codice hash di un intero con segno a 32 bit.

Si applica a