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);
static member GetHashCode : obj -> int
Public Shared Function GetHashCode (o As Object) As Integer

参数

o
Object

要检索其哈希代码的对象。An object to retrieve the hash code for.

返回

o 参数标识的对象的哈希代码。A hash code for the object identified by the o parameter.

示例

下面的示例说明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

注解

方法始终以非虚拟Object.GetHashCode方式调用方法, 即使对象Object.GetHashCode的类型已重写方法。 RuntimeHelpers.GetHashCodeThe 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.

警告

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.

重要

请注意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

公共语言运行时 (CLR) 维护字符串的内部池, 并将文本存储在池中。The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. 如果两个字符串 ( str1例如和str2) 是从相同的字符串文本组成的, 则 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是作为串联操作的结果创建的, 并且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.

适用于

另请参阅