Object.GetHashCode Object.GetHashCode Object.GetHashCode Object.GetHashCode Method

定义

作为默认哈希函数。Serves as the default hash function.

public:
 virtual int GetHashCode();
public virtual int GetHashCode ();
abstract member GetHashCode : unit -> int
override this.GetHashCode : unit -> int
Public Overridable Function GetHashCode () As Integer

返回

当前对象的哈希代码。A hash code for the current object.

示例

为具有相同或更小范围Int32的数字值计算哈希代码的最简单方法之一是只返回该值。One of the simplest ways to compute a hash code for a numeric value that has the same or a smaller range than the Int32 type is to simply return that value. 下面的示例演示了一个Number结构的实现。The following example shows such an implementation for a Number structure.

using System;

public struct Number
{
   private int n;

   public Number(int value)
   {
      n = value;
   }

   public int Value
   {
      get { return n; }
   }
   
   public override bool Equals(Object obj)
   {
      if (obj == null || ! (obj is Number)) 
         return false;
      else
         return n == ((Number) obj).n;
   }      
   
   public override int GetHashCode()
   {
      return n;
   }
   
   public override string ToString()
   {
      return n.ToString();
   }
}

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      for (int ctr = 0; ctr <= 9; ctr++) {
         int randomN = rnd.Next(Int32.MinValue, Int32.MaxValue);
         Number n = new Number(randomN);
         Console.WriteLine("n = {0,12}, hash code = {1,12}", n, n.GetHashCode());
      }   
   }
}
// The example displays output like the following:
//       n =   -634398368, hash code =   -634398368
//       n =   2136747730, hash code =   2136747730
//       n =  -1973417279, hash code =  -1973417279
//       n =   1101478715, hash code =   1101478715
//       n =   2078057429, hash code =   2078057429
//       n =   -334489950, hash code =   -334489950
//       n =    -68958230, hash code =    -68958230
//       n =   -379951485, hash code =   -379951485
//       n =    -31553685, hash code =    -31553685
//       n =   2105429592, hash code =   2105429592
Public Structure Number
   Private n As Integer

   Public Sub New(value As Integer)
      n = value
   End Sub

   Public ReadOnly Property Value As Integer
      Get
         Return n
      End Get
   End Property
   
   Public Overrides Function Equals(obj As Object) As Boolean
      If obj Is Nothing OrElse Not TypeOf obj Is Number Then
         Return False
      Else
         Return n = CType(obj, Number).n
      End If
   End Function      
   
   Public Overrides Function GetHashCode() As Integer
      Return n
   End Function
   
   Public Overrides Function ToString() As String
      Return n.ToString()
   End Function
End Structure

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      For ctr As Integer = 0 To 9
         Dim randomN As Integer = rnd.Next(Int32.MinValue, Int32.MaxValue)
         Dim n As New Number(randomN)
         Console.WriteLine("n = {0,12}, hash code = {1,12}", n, n.GetHashCode())
      Next
   End Sub
End Module
' The example displays output like the following:
'       n =   -634398368, hash code =   -634398368
'       n =   2136747730, hash code =   2136747730
'       n =  -1973417279, hash code =  -1973417279
'       n =   1101478715, hash code =   1101478715
'       n =   2078057429, hash code =   2078057429
'       n =   -334489950, hash code =   -334489950
'       n =    -68958230, hash code =    -68958230
'       n =   -379951485, hash code =   -379951485
'       n =    -31553685, hash code =    -31553685
'       n =   2105429592, hash code =   2105429592

通常,类型具有多个数据字段,这些字段可参与生成哈希代码。Frequently, a type has multiple data fields that can participate in generating the hash code. 生成哈希代码的一种方法是使用XOR (eXclusive OR)操作来合并这些字段,如以下示例中所示。One way to generate a hash code is to combine these fields using an XOR (eXclusive OR) operation, as shown in the following example.

using System;

// A type that represents a 2-D point.
public struct Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
       this.x = x;
       this.y = y;
    }
    
    public override bool Equals(Object obj)
    {
       if (! (obj is Point)) return false;
       
       Point p = (Point) obj;
       return x == p.x & y == p.y;
    }
    
    public override int GetHashCode()
    { 
        return x ^ y;
    } 
} 

public class Example
{
   public static void Main()
   {
      Point pt = new Point(5, 8);
      Console.WriteLine(pt.GetHashCode());
        
      pt = new Point(8, 5);
      Console.WriteLine(pt.GetHashCode());
   }
}
// The example displays the following output:
//       13
//       13
' A type that represents a 2-D point.
Public Structure Point
    Private x As Integer
    Private y As Integer

    Public Sub New(x As Integer, y As Integer)
       Me.x = x
       Me.y = y
    End Sub
    
    Public Overrides Function Equals(obj As Object) As Boolean
       If Not TypeOf obj Is Point Then Return False
       
       Dim p As Point = CType(obj, Point)
       Return x = p.x And y = p.y
    End Function
    
    Public Overrides Function GetHashCode() As Integer 
        Return x Xor y
    End Function 
End Structure 

Public Module Example
   Public Sub Main() 
      Dim pt As New Point(5, 8)
      Console.WriteLine(pt.GetHashCode())
        
      pt = New Point(8, 5)
      Console.WriteLine(pt.GetHashCode())
   End Sub 
End Module   

前面的示例返回相同的哈希代码(n1、n2)和(n2,n1),因此可能会产生比预期更多的冲突。The previous example returns the same hash code for (n1, n2) and (n2, n1), and so may generate more collisions than are desirable. 提供了许多解决方案,以便这些情况下的哈希代码不完全相同。A number of solutions are available so that hash codes in these cases are not identical. 一种是返回Tuple对象的哈希代码,该对象反映每个字段的顺序。One is to return the hash code of a Tuple object that reflects the order of each field. 下面的示例演示使用Tuple<T1,T2>类的可能的实现。The following example shows a possible implementation that uses the Tuple<T1,T2> class. 但请注意,实例化Tuple对象的性能开销可能会显著影响在哈希表中存储大量对象的应用程序的整体性能。Note, though, that the performance overhead of instantiating a Tuple object may significantly impact the overall performance of an application that stores large numbers of objects in hash tables.

using System;

public struct Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
       this.x = x;
       this.y = y;
    }
    
    public override bool Equals(Object obj)
    {
       if (!(obj is Point)) return false;
       
       Point p = (Point) obj;
       return x == p.x & y == p.y;
    }
    
    public override int GetHashCode()
    { 
        return Tuple.Create(x, y).GetHashCode();
    } 
} 

public class Example
{
   public static void Main()
   {
        Point pt = new Point(5, 8);
        Console.WriteLine(pt.GetHashCode());
        
        pt = new Point(8, 5);
        Console.WriteLine(pt.GetHashCode());
   }
}
// The example displays the following output:
//       173
//       269
Public Structure Point
    Private x As Integer
    Private y As Integer

    Public Sub New(x As Integer, y As Integer)
       Me.x = x
       Me.y = y
    End Sub
    
    Public Overrides Function Equals(obj As Object) As Boolean
       If Not TypeOf obj Is Point Then Return False
       
       Dim p As Point = CType(obj, Point)
       Return x = p.x And y = p.y
    End Function
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(x, y).GetHashCode()
    End Function 
End Structure 

Public Module Example
    Public Sub Main() 
        Dim pt As New Point(5, 8)
        Console.WriteLine(pt.GetHashCode())
        
        pt = New Point(8, 5)
        Console.WriteLine(pt.GetHashCode())
    End Sub 
End Module         
' The example displays the following output:
'       173
'       269

第二种替代解决方案涉及通过将连续字段的哈希代码左移两位或更多位,来加权单个哈希代码。A second alternative solution involves weighting the individual hash codes by left-shifting the hash codes of successive fields by two or more bits. 最佳方式,而不是被丢弃,超过位31的位应换行,而不是丢弃。Optimally, instead of being discarded, bits shifted beyond bit 31 should wrap around rather than be discarded. 由于C#和 Visual Basic 中的左移运算符会丢弃 bits,这需要创建左移和换行方法,如下所示:Since bits are discarded by the left-shift operators in both C# and Visual Basic, this requires creating a left shift-and-wrap method like the following:

public int ShiftAndWrap(int value, int positions)
{
    positions = positions & 0x1F;
  
    // Save the existing bit pattern, but interpret it as an unsigned integer.
    uint number = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0);
    // Preserve the bits to be discarded.
    uint wrapped = number >> (32 - positions);
    // Shift and wrap the discarded bits.
    return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0);
}
Public Function ShiftAndWrap(value As Integer, positions As Integer) As Integer
   positions = positions And &h1F
   
   ' Save the existing bit pattern, but interpret it as an unsigned integer.
   Dim number As UInteger = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0)
   ' Preserve the bits to be discarded.
   Dim wrapped AS UInteger = number >> (32 - positions)
   ' Shift and wrap the discarded bits.
   Return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) Or wrapped), 0)
End Function

然后,下面的示例使用此 shift 和 wrap 方法计算前面的示例中使用的Point结构的哈希代码。The following example then uses this shift-and-wrap method to compute the hash code of the Point structure used in the previous examples.

using System;

public struct Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
       this.x = x;
       this.y = y;
    }
    
    public override bool Equals(Object obj)
    {
       if (!(obj is Point)) return false;
       
       Point p = (Point) obj;
       return x == p.x & y == p.y;
    }
    
    public override int GetHashCode()
    { 
        return ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode();
    } 
    
    private int ShiftAndWrap(int value, int positions)
    {
        positions = positions & 0x1F;
      
        // Save the existing bit pattern, but interpret it as an unsigned integer.
        uint number = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0);
        // Preserve the bits to be discarded.
        uint wrapped = number >> (32 - positions);
        // Shift and wrap the discarded bits.
        return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0);
    }
} 

public class Example
{
   public static void Main()
   {
        Point pt = new Point(5, 8);
        Console.WriteLine(pt.GetHashCode());
        
        pt = new Point(8, 5);
        Console.WriteLine(pt.GetHashCode());
   }
}
// The example displays the following output:
//       28
//       37 
Public Structure Point
    Private x As Integer
    Private y As Integer

    Public Sub New(x As Integer, y As Integer)
       Me.x = x
       Me.y = y
    End Sub
    
    Public Overrides Function Equals(obj As Object) As Boolean
       If Not TypeOf obj Is Point Then Return False
       
       Dim p As Point = CType(obj, Point)
       Return x = p.x And y = p.y
    End Function
    
    Public Overrides Function GetHashCode() As Integer 
        Return ShiftAndWrap(x.GetHashCode(), 2) XOr y.GetHashCode()
    End Function 
    
    Private Function ShiftAndWrap(value As Integer, positions As Integer) As Integer
        positions = positions And &h1F
      
        ' Save the existing bit pattern, but interpret it as an unsigned integer.
        Dim number As UInteger = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0)
        ' Preserve the bits to be discarded.
        Dim wrapped AS UInteger = number >> (32 - positions)
        ' Shift and wrap the discarded bits.
        Return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) Or wrapped), 0)
    End Function
End Structure 

Module Example
   Public Sub Main()
        Dim pt As New Point(5, 8)
        Console.WriteLine(pt.GetHashCode())
        
        pt = New Point(8, 5)
        Console.WriteLine(pt.GetHashCode())
   End Sub
End Module
' The example displays the following output:
'       28
'       37

注解

哈希代码是一个数字值,用于在基于哈希的集合( Dictionary<TKey,TValue>如类Hashtable 、类或从DictionaryBase类派生的类型)中插入和标识对象。A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey,TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. GetHashCode方法为需要快速检查对象相等性的算法提供此哈希代码。The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

备注

有关哈希表中的哈希代码和其他哈希代码算法如何使用哈希代码的信息,请参阅维基百科中的哈希函数条目。For information about how hash codes are used in hash tables and for some additional hash code algorithms, see the Hash Function entry in Wikipedia.

相等的两个对象返回的哈希代码相等。Two objects that are equal return hash codes that are equal. 但是,反之亦然:相等的哈希代码不意味着对象相等,因为不同(不相等)对象可以具有相同的哈希代码。However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes. 此外,.net 不保证GetHashCode方法的默认实现,并且此方法返回的值可能在 .net 实现之间有所不同,例如 .NET Framework 和 .net Core 的不同版本以及平台(如32位和64位平台。Furthermore, .NET does not guarantee the default implementation of the GetHashCode method, and the value this method returns may differ between .NET implementations, such as different versions of .NET Framework and .NET Core, and platforms, such as 32-bit and 64-bit platforms. 出于这些原因,请不要将此方法的默认实现用作唯一对象标识符以进行哈希处理。For these reasons, do not use the default implementation of this method as a unique object identifier for hashing purposes. 下面是两个结果:Two consequences follow from this:

  • 不应假定相等哈希代码意味着对象相等。You should not assume that equal hash codes imply object equality.

  • 永远不应在创建它的应用程序域之外保留或使用哈希代码,因为相同的对象可能会在应用程序域、进程和平台之间进行哈希运算。You should never persist or use a hash code outside the application domain in which it was created, because the same object may hash across application domains, processes, and platforms.

警告

哈希代码适用于基于哈希表的集合中的高效插入和查找。A hash code is intended for efficient insertion and lookup in collections that are based on a hash table. 哈希代码不是永久值。A hash code is not a permanent value. 出于此原因:For this reason:

  • 不要序列化哈希代码值或将其存储在数据库中。Do not serialize hash code values or store them in databases.
  • 不要使用哈希代码作为密钥来检索键控集合中的对象。Do not use the hash code as the key to retrieve an object from a keyed collection.
  • 不要跨应用程序域或进程发送哈希代码。Do not send hash codes across application domains or processes. 在某些情况下,可以基于每个进程或每个应用程序域来计算哈希代码。In some cases, hash codes may be computed on a per-process or per-application domain basis.
  • 如果需要加密型强哈希,请不要使用哈希代码(而不是加密哈希函数返回的值)。Do not use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. 对于加密哈希,请使用派生自System.Security.Cryptography.HashAlgorithmSystem.Security.Cryptography.KeyedHashAlgorithm类的类。For cryptographic hashes, use a class derived from the System.Security.Cryptography.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm class.
  • 不要测试哈希代码是否相等,以确定两个对象是否相等。Do not test for equality of hash codes to determine whether two objects are equal. (不相等的对象可以具有相同的哈希代码。)若要测试是否相等,请ReferenceEquals调用Equals或方法。(Unequal objects can have identical hash codes.) To test for equality, call the ReferenceEquals or Equals method.

GetHashCode方法可由派生类型重写。The GetHashCode method can be overridden by a derived type. 如果GetHashCode未重写,则通过Object.GetHashCode调用基类的方法计算引用类型的哈希代码,该方法根据对象的引用计算哈希代码; 有关详细信息,请参阅RuntimeHelpers.GetHashCodeIf GetHashCode is not overridden, hash codes for reference types are computed by calling the Object.GetHashCode method of the base class, which computes a hash code based on an object's reference; for more information, see RuntimeHelpers.GetHashCode. 换言之,该ReferenceEquals方法返回true的两个对象具有相同的哈希代码。In other words, two objects for which the ReferenceEquals method returns true have identical hash codes. 如果值类型不重写GetHashCode,则ValueType.GetHashCode基类的方法使用反射根据类型字段的值来计算哈希代码。If value types do not override GetHashCode, the ValueType.GetHashCode method of the base class uses reflection to compute the hash code based on the values of the type's fields. 换句话说,其字段具有相等值的值类型具有相同的哈希代码。In other words, value types whose fields have equal values have equal hash codes. 有关替代GetHashCode的详细信息,请参阅 "对继承者的说明" 部分。For more information about overriding GetHashCode, see the "Notes to Inheritors" section.

警告

如果重写GetHashCode方法,则还应重写Equals,反之亦然。If you override the GetHashCode method, you should also override Equals, and vice versa. 如果在测试Equals两个true对象是否相等时重写的方法返回, GetHashCode则重写的方法必须为这两个对象返回相同的值。If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

如果用作哈希表中的键的对象不提供有用的GetHashCode实现,则可以通过向Hashtable类构造函数的重载之一IEqualityComparer提供实现来指定哈希代码提供程序。If an object that is used as a key in a hash table does not provide a useful implementation of GetHashCode, you can specify a hash code provider by supplying an IEqualityComparer implementation to one of the overloads of the Hashtable class constructor.

说明Windows 运行时Windows RuntimeNotes for the Windows 运行时Windows Runtime

当你在Windows 运行时Windows RuntimeGetHashCode的类上调用方法时,它将为不重写GetHashCode的类提供默认行为。When you call the GetHashCode method on a class in the Windows 运行时Windows Runtime, it provides the default behavior for classes that don't override GetHashCode. 这是 .NET Framework 为Windows 运行时Windows Runtime提供的支持的一部分(请参阅Windows 应用商店应用和 Windows 运行时的 .NET Framework 支持)。This is part of the support that the .NET Framework provides for the Windows 运行时Windows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). 中的Windows 运行时Windows Runtime类不继承Object,当前未实现。 GetHashCodeClasses in the Windows 运行时Windows Runtime don't inherit Object, and currently don't implement a GetHashCode. 但是,当ToString你在C#或 Visual Basic Equals(Object)代码中GetHashCode使用它们时,它们看起来具有、和方法,而 .NET Framework 提供这些方法的默认行为。However, they appear to have ToString, Equals(Object), and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods.

备注

Windows 运行时Windows Runtime用C#或 Visual Basic 编写的GetHashCode类可以重写方法。classes that are written in C# or Visual Basic can override the GetHashCode method.

继承者说明

使用哈希函数可以快速生成与对象的值相对应的数字(哈希代码)。A hash function is used to quickly generate a number (hash code) that corresponds to the value of an object. 哈希函数通常是特定于每个类型的,因此,为实现唯一性,必须使用至少一个实例字段作为输入。Hash functions are usually specific to each type and, for uniqueness, must use at least one of the instance fields as input. 不应使用静态字段的值来计算哈希代码。Hash codes should not be computed by using the values of static fields.

对于派生自Object的类,只有当派生类将相等定义GetHashCode()为引用相等性时,该GetHashCode方法才能委托给基类实现。For classes derived from Object, the GetHashCode method can delegate to the base class GetHashCode() implementation only if the derived class defines equality to be reference equality. GetHashCode()对于引用类型,的默认实现返回的哈希代码等效于GetHashCode(Object)方法返回的哈希代码。The default implementation of GetHashCode() for reference types returns a hash code that is equivalent to the one returned by the GetHashCode(Object) method. 可对不可GetHashCode()变引用类型重写。You can override GetHashCode() for immutable reference types. 通常,对于可变引用类型,应仅在以下GetHashCode()情况下重写:In general, for mutable reference types, you should override GetHashCode() only if: -可以计算不可变的字段中的哈希代码;或- You can compute the hash code from fields that are not mutable; or -可以确保可变对象的哈希代码在依赖于其哈希代码的集合中时不会更改。- You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

否则,你可能会认为可变对象会在哈希表中丢失。Otherwise, you might think that the mutable object is lost in the hash table. 如果选择替代GetHashCode()可变引用类型,您的文档应清楚地说明,当对象存储在哈希表中时,您的类型的用户不应修改对象值。If you do choose to override GetHashCode() for a mutable reference type, your documentation should make it clear that users of your type should not modify object values while the object is stored in a hash table.

对于值类型, GetHashCode()提供使用反射的默认哈希代码实现。For value types, GetHashCode() provides a default hash code implementation that uses reflection. 你应考虑重写它以获得更好的性能。You should consider overriding it for better performance.


有关以各种方式计算哈希代码的详细信息和示例,请参阅 "示例" 部分。For more information and examples that compute hash codes in a variety of ways, see the Examples section.

哈希函数必须具有以下属性:A hash function must have the following properties: -如果两个对象的比较结果相等GetHashCode() ,则每个对象的方法必须返回相同的值。- If two objects compare as equal, the GetHashCode() method for each object must return the same value. 但是,如果两个对象的比较结果不相等, GetHashCode()则这两个对象的方法不必返回不同的值。However, if two objects do not compare as equal, the GetHashCode() methods for the two objects do not have to return different values. -对于GetHashCode()对象状态不会修改确定对象的[system.object](xref:System.Object.Equals*)方法返回值的对象状态,对象的方法必须始终返回相同的哈希代码。- The GetHashCode() method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's [System.Object.Equals](xref:System.Object.Equals*) method. 请注意,这仅适用于当前执行的应用程序,并且如果重新运行应用程序,则可以返回不同的哈希代码。Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again. -为了获得最佳性能,哈希函数应为所有输入生成偶数分布,其中包括大量聚集输入。- For the best performance, a hash function should generate an even distribution for all input, including input that is heavily clustered. 这意味着,对对象状态的小修改应该会导致对生成的哈希代码进行较大的修改,以获得最佳的哈希表性能。An implication is that small modifications to object state should result in large modifications to the resulting hash code for best hash table performance. -哈希函数的计算成本应较低。- Hash functions should be inexpensive to compute. GetHashCode() -方法不应引发异常。- The GetHashCode() method should not throw exceptions. 例如, GetHashCode() String类提供的方法的实现返回相同字符串值的相同哈希代码。For example, the implementation of the GetHashCode() method provided by the String class returns identical hash codes for identical string values. 因此,如果String两个对象表示相同的字符串值,则它将返回相同的哈希代码。Therefore, two String objects return the same hash code if they represent the same string value. 此外,该方法使用字符串中的所有字符生成合理随机分发的输出,即使在某些范围内对输入进行群集(例如,许多用户的字符串可能只包含低于128的 ASCII 字符,但字符串可以包含任何 65535 Unicode 字符)。Also, the method uses all the characters in the string to generate reasonably randomly distributed output, even when the input is clustered in certain ranges (for example, many users might have strings that contain only the lower 128 ASCII characters, even though a string can contain any of the 65,535 Unicode characters). 在类上提供良好的哈希函数可能会显著影响将这些对象添加到哈希表的性能。Providing a good hash function on a class can significantly affect the performance of adding those objects to a hash table. 在具有提供哈希函数的良好实现的键的哈希表中,搜索元素会采用固定时间(例如,O (1)操作)。In a hash table with keys that provide a good implementation of a hash function, searching for an element takes constant time (for example, an O(1) operation). 在包含哈希函数实现的哈希表中,搜索的性能取决于哈希表中的项数(例如,O (`n`)运算),其中`n`是哈希表中的项数。In a hash table with a poor implementation of a hash function, the performance of a search depends on the number of items in the hash table (for example, an O(`n`) operation, where `n` is the number of items in the hash table). 恶意用户可以输入增加冲突数量的数据,这可能会显著降低依赖于哈希表的应用程序的性能,但在以下情况下:A malicious user can input data that increases the number of collisions, which can significantly degrade the performance of applications that depend on hash tables, under the following conditions: -哈希函数产生频繁冲突。- When hash functions produce frequent collisions. -当哈希表中的大量对象产生相等或近似相等的哈希代码时。- When a large proportion of objects in a hash table produce hash codes that are equal or approximately equal to one another. -当用户输入从中计算哈希代码的数据时。- When users input the data from which the hash code is computed. 重写GetHashCode()的派生类还必须Equals(Object)重写以确保两个被视为相等的对象具有相同的哈希Hashtable代码; 否则,该类型可能无法正常工作。Derived classes that override GetHashCode() must also override Equals(Object) to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly.

适用于

另请参阅