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

比較で使用する規則を指定する列挙値の 1 つ。

戻り値

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

比較で使用する規則を指定する列挙値の 1 つ。

戻り値

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パフォーマンスを向上するためです。

重要

2 つの文字列オブジェクトが等しい場合、メソッドは GetHashCode 同じ値を返します。 ただし、一意の文字列値ごとに一意のハッシュ コード値はありません。 異なる文字列で同じハッシュ コードを返すことができます。

ハッシュ コード自体が安定するとは限りません。 同一の文字列のハッシュ コードは、.NET の実装、.NET バージョン、および .NET プラットフォーム (32 ビットや 64 ビットなど) で、1 つのバージョンの .NET で異なる場合があります。 場合によっては、アプリケーション ドメインによって異なる場合もあります。 これは、同じプログラムの後続の 2 回の実行で異なるハッシュ コードが返される可能性があることを意味します。

その結果、ハッシュ コードは、作成されたアプリケーション ドメインの外部で使用しないでください。また、コレクション内のキー フィールドとして使用したり、永続化したりしないでください。

最後に、暗号的に強力なハッシュが必要な場合は、暗号化ハッシュ関数によって返される値の代わりにハッシュ コードを使用しないでください。 暗号化ハッシュの場合は、 クラスまたは System.Security.Cryptography.KeyedHashAlgorithm クラスから派生したクラスをSystem.Security.Cryptography.HashAlgorithm使用します。

ハッシュ コードの詳細については、「」を参照してください Object.GetHashCode

.NET Frameworkデスクトップ アプリでは、UseRandomizedStringHashAlgorithm> 要素を使用<して、アプリケーション ドメインごとに一意のハッシュ コードを生成できます。 これにより、競合の数を減らし、ハッシュ テーブルを使用する挿入と参照の全体的なパフォーマンスを向上させることができます。 次の例は、UseRandomizedStringHashAlgorithm> 要素の<使用方法を示しています。 プライベート文字列定数 sDisplayString含むクラスを定義します。値は "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

構成ファイルを指定せずにこの例を実行すると、次のような出力が表示されます。 文字列のハッシュ コードが 2 つアプリケーション ドメインで同じであることに注意してください。

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() 返される値はプラットフォームに依存します。 .NET Frameworkの 32 ビットバージョンと 64 ビット バージョンでは異なります。 また、.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 ビット符号付き整数ハッシュ コード。

適用対象