RuntimeHelpers.GetHashCode(Object) Method

Definition

做為特定物件的雜湊函式,適合在使用雜湊碼之雜湊演算法及資料結構中使用。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);
static member GetHashCode : obj -> int
Public Shared Function GetHashCode (o As Object) As Integer

Parameters

o
Object

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

Returns

Int32

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

Examples

下列範例示範 Object.GetHashCodeRuntimeHelpers.GetHashCode 方法之間的差異。The 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.Format 方法所傳回。Although 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.GetHashCode所產生的雜湊碼相同。In 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

Remarks

即使物件的類型已覆寫 Object.GetHashCode 方法,RuntimeHelpers.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 可能會與 Object.GetHashCode 方法直接在物件上呼叫 GetHashCode 不同。Therefore, using RuntimeHelpers.GetHashCode might differ from calling GetHashCode directly on the object with the Object.GetHashCode method.

Warning

雖然 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.GetHashCode傳回相同的值。For 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.

Important

請注意,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 會將 str1str2 設定為指向受控堆積上的相同位置,以節省記憶體。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 是建立為串連作業的結果,而 str2str1相同,則在這兩個字串物件上使用 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.

Applies to

See also