RuntimeHelpers.GetHashCode(Object) 方法

定義

做為特定物件的雜湊函式,適合在使用雜湊碼之雜湊演算法及資料結構中使用。Serves as a hash function for a particular object, and is suitable for use in algorithms and data structures that use hash codes, such as a hash table.

public:
 static int GetHashCode(System::Object ^ o);
public static int GetHashCode (object o);
public static int GetHashCode (object? o);
static member GetHashCode : obj -> int
Public Shared Function GetHashCode (o As Object) As Integer

參數

o
Object

要為其擷取雜湊程式碼的物件。An object to retrieve the hash code for.

傳回

Int32

o 參數所識別之物件的雜湊碼。A hash code for the object identified by the o parameter.

範例

下列範例示範和方法之間的差異 Object.GetHashCode RuntimeHelpers.GetHashCodeThe following example demonstrates the difference between the Object.GetHashCode and RuntimeHelpers.GetHashCode methods. 範例的輸出說明下列各項:The output from the example illustrates the following:

  • 傳遞給方法的第一組字串的兩組雜湊碼 ShowHashCodes 都不相同,因為字串完全不同。Both sets of hash codes for the first set of strings passed to the ShowHashCodes method are different, because the strings are completely different.

  • Object.GetHashCode 針對傳遞給方法的第二組字串產生相同的雜湊程式碼 ShowHashCodes ,因為字串相等。Object.GetHashCode generates the same hash code for the second set of strings passed to the ShowHashCodes method, because the strings are equal. 不過,此 RuntimeHelpers.GetHashCode 方法不會。However, the RuntimeHelpers.GetHashCode method does not. 第一個字串是使用字串常值來定義,因此會進行暫存。The first string is defined by using a string literal and so is interned. 雖然第二個字串的值是相同的,但它並不會被留用,因為呼叫方法會傳回它 String.FormatAlthough the value of the second string is the same, it is not interned, because it is returned by a call to the String.Format method.

  • 在第三個字串的情況下,針對兩個字串所產生的雜湊程式碼與 Object.GetHashCode 產生的雜湊碼相同 RuntimeHelpers.GetHashCodeIn the case of the third string, the hash codes produced by Object.GetHashCode for both strings are identical, as are the hash codes produced by RuntimeHelpers.GetHashCode. 這是因為編譯器已將指派給這兩個字串的值視為單一字串常值,因此字串變數會參考相同的留用字串。This is because the compiler has treated the value assigned to both strings as a single string literal, and so the string variables refer to the same interned string.

using System;
using System.Runtime.CompilerServices;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("{0,-18} {1,6} {2,18:N0}    {3,6} {4,18:N0}\n",
                        "", "Var 1", "Hash Code", "Var 2", "Hash Code");
      
      // Get hash codes of two different strings.
      String sc1 = "String #1";
      String sc2 = "String #2";
      ShowHashCodes("sc1", sc1, "sc2", sc2);
 
      // Get hash codes of two identical non-interned strings.
      String s1 = "This string";
      String s2 = String.Format("{0} {1}", "This", "string");
      ShowHashCodes("s1", s1, "s2", s2);

      // Get hash codes of two (evidently concatenated) strings.
      String si1 = "This is a string!";
      String si2 = "This " + "is " + "a " + "string!";
      ShowHashCodes("si1", si1, "si2", si2);
   }

   private static void ShowHashCodes(String var1, Object value1, 
                                     String var2, Object value2)
   {
      Console.WriteLine("{0,-18} {1,6} {2,18:X8}    {3,6} {4,18:X8}",
                        "Obj.GetHashCode", var1, value1.GetHashCode(),
                        var2, value2.GetHashCode());

      Console.WriteLine("{0,-18} {1,6} {2,18:X8}    {3,6} {4,18:X8}\n",
                        "RTH.GetHashCode", var1, RuntimeHelpers.GetHashCode(value1),
                        var2, RuntimeHelpers.GetHashCode(value2));
   }
}
// The example displays output similar to the following:
//                        Var 1          Hash Code     Var 2          Hash Code
//    
//    Obj.GetHashCode       sc1           94EABD27       sc2           94EABD24
//    RTH.GetHashCode       sc1           02BF8098       sc2           00BB8560
//    
//    Obj.GetHashCode        s1           29C5A397        s2           29C5A397
//    RTH.GetHashCode        s1           0297B065        s2           03553390
//    
//    Obj.GetHashCode       si1           941BCEA5       si2           941BCEA5
//    RTH.GetHashCode       si1           01FED012       si2           01FED012
Imports System.Runtime.CompilerServices

Module Example
   Public Sub Main()
      Console.WriteLine("{0,-18} {1,6} {2,18:N0}    {3,6} {4,18:N0}",
                        "", "Var 1", "Hash Code", "Var 2", "Hash Code")
      Console.WriteLine()
      
      ' Get hash codes of two different strings.
      Dim sc1 As String = "String #1"
      Dim sc2 As String = "String #2"
      ShowHashCodes("sc1", sc1, "sc2", sc2)
 
      ' Get hash codes of two identical non-interned strings.
      Dim s1 As String = "This string"
      Dim s2 As String = String.Format("{0} {1}", "This", "string")
      ShowHashCodes("s1", s1, "s2", s2)

      ' Get hash codes of two (evidently concatenated) strings.
      Dim si1 As String = "This is a string!"
      Dim si2 As String = "This " + "is " + "a " + "string!"
      ShowHashCodes("si1", si1, "si2", si2)
   End Sub
   
   Private Sub ShowHashCodes(var1 As String, value1 As Object, 
                             var2 As String, value2 As Object)
      Console.WriteLine("{0,-18} {1,6} {2,18:X8}    {3,6} {4,18:X8}",
                        "Obj.GetHashCode", var1, value1.GetHashCode,
                        var2, value2.GetHashCode)

      Console.WriteLine("{0,-18} {1,6} {2,18:X8}    {3,6} {4,18:X8}",
                        "RTH.GetHashCode", var1, RuntimeHelpers.GetHashCode(value1),
                        var2, RuntimeHelpers.GetHashCode(value2))
      Console.WriteLine()
   End Sub
End Module
' The example displays output similar to the following:
'                        Var 1          Hash Code     Var 2          Hash Code
'    
'    Obj.GetHashCode       sc1           94EABD27       sc2           94EABD24
'    RTH.GetHashCode       sc1           02BF8098       sc2           00BB8560
'    
'    Obj.GetHashCode        s1           29C5A397        s2           29C5A397
'    RTH.GetHashCode        s1           0297B065        s2           03553390
'    
'    Obj.GetHashCode       si1           941BCEA5       si2           941BCEA5
'    RTH.GetHashCode       si1           01FED012       si2           01FED012

備註

RuntimeHelpers.GetHashCode方法一律會以 Object.GetHashCode 非虛擬方式呼叫方法,即使物件的型別已覆寫 Object.GetHashCode 方法。The RuntimeHelpers.GetHashCode method always calls the Object.GetHashCode method non-virtually, even if the object's type has overridden the Object.GetHashCode method. 因此,使用 RuntimeHelpers.GetHashCode 可能不同于 GetHashCode 使用方法直接在物件上呼叫 Object.GetHashCodeTherefore, using RuntimeHelpers.GetHashCode might differ from calling GetHashCode directly on the object with the Object.GetHashCode method.

警告

雖然 RuntimeHelpers.GetHashCode 方法會針對相同的物件參考傳回相同的雜湊碼,但您不應該使用這個方法來測試物件識別,因為此雜湊程式碼不會唯一識別物件參考。Although the RuntimeHelpers.GetHashCode method returns identical hash codes for identical object references, you should not use this method to test for object identity, because this hash code does not uniquely identify an object reference. 若要測試物件識別 (也就是,若要測試兩個物件是否參考記憶體) 中的相同物件,請呼叫 Object.ReferenceEquals 方法。To test for object identify (that is, to test that two objects reference the same object in memory), call the Object.ReferenceEquals method. 您也應該使用 GetHashCode 來測試兩個字串是否代表相等的物件參考,因為此字串會被留用。Nor should you use GetHashCode to test whether two strings represent equal object references, because the string is interned. 若要測試字串暫留,請呼叫 String.IsInterned 方法。To test for string interning, call the String.IsInterned method.

Object.GetHashCodeRuntimeHelpers.GetHashCode 方法的差異如下:The Object.GetHashCode and RuntimeHelpers.GetHashCode methods differ as follows:

  • Object.GetHashCode 傳回以物件的相等定義為基礎的雜湊碼。Object.GetHashCode returns a hash code that is based on the object's definition of equality. 例如,兩個具有相同內容的字串會傳回相同的值 Object.GetHashCodeFor example, two strings with identical contents will return the same value for Object.GetHashCode.

  • RuntimeHelpers.GetHashCode 傳回表示物件識別的雜湊碼。RuntimeHelpers.GetHashCode returns a hash code that indicates object identity. 也就是兩個字串變數,其內容完全相同,且代表暫存的字串 (請參閱 [ 字串暫存 ] 區段) 或代表記憶體中的單一字串傳回相同的雜湊碼。That is, two string variables whose contents are identical and that represent a string that is interned (see the String Interning section) or that represent a single string in memory return identical hash codes.

重要

請注意, GetHashCode 對於相等的物件參考,一律會傳回相同的雜湊碼。Note that GetHashCode always returns identical hash codes for equal object references. 不過,反向並不成立:相等的雜湊碼不表示相等的物件參考。However, the reverse is not true: equal hash codes do not indicate equal object references. 特定的雜湊碼值不是特定物件參考的唯一值;不同的物件參考可以產生相同的雜湊碼。A particular hash code value is not unique to a particular object reference; different object references can generate identical hash codes.

編譯器會使用這個方法。This method is used by compilers.

字串暫留String Interning

Common language runtime (CLR) 會維護內部的字串集區,並將常值儲存在集區中。The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. 例如,如果兩個字串 (, str1str2) 是由相同的字串常值所組成,則 CLR 會將設定 str1 str2 為指向 managed 堆積上的相同位置,以節省記憶體。If two strings (for example, str1 and str2) are formed from an identical string literal, the CLR will set str1 and str2 to point to the same location on the managed heap to conserve memory. RuntimeHelpers.GetHashCode在這兩個字串物件上呼叫,將會產生相同的雜湊碼,與上一節中的第二個專案符號專案相反。Calling RuntimeHelpers.GetHashCode on these two string objects will produce the same hash code, contrary to the second bulleted item in the previous section.

CLR 只會將常值新增至集區。The CLR adds only literals to the pool. 字串作業的結果(例如串連)不會加入至集區,除非編譯器將字串串連解析為單一字串常值。Results of string operations such as concatenation are not added to the pool, unless the compiler resolves the string concatenation as a single string literal. 因此,如果 str2 是建立為串連作業的結果,而且與 str2 相同 str1 ,則 RuntimeHelpers.GetHashCode 在這兩個字串物件上使用,將不會產生相同的雜湊碼。Therefore, if str2 was created as the result of a concatenation operation, and str2 is identical to str1, using RuntimeHelpers.GetHashCode on these two string objects will not produce the same hash code.

如果您想要明確地將串連的字串新增至集區,請使用 String.Intern 方法。If you want to add a concatenated string to the pool explicitly, use the String.Intern method.

您也可以使用 String.IsInterned 方法來檢查字串是否有暫存參考。You can also use the String.IsInterned method to check whether a string has an interned reference.

適用於

另請參閱