Object.GetHashCode 方法

定義

做為預設雜湊函式。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

接著,下列範例會使用此換行方法來計算先前範例中所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.

衍生類型可以覆寫方法。GetHashCodeThe GetHashCode method can be overridden by a derived type. 如果GetHashCode未覆寫,則會藉由Object.GetHashCode呼叫基類的方法來計算參考型別的雜湊碼,其會根據物件的參考來計算雜湊碼。如需詳細資訊RuntimeHelpers.GetHashCode,請參閱。If 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索引鍵的物件未提供的實用執行,您可以藉由IEqualityComparer提供實作為Hashtable類別處理常式的其中一個多載來指定雜湊碼提供者。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

當您在的GetHashCode Windows 執行階段Windows Runtime類別上呼叫方法時,它會為不會覆寫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 Store 應用程式的 .NET Framework 支援和 Windows 執行階段)。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繼承, GetHashCode而且目前不會執行。Classes in the Windows 執行階段Windows Runtime don't inherit Object, and currently don't implement a GetHashCode. 不過,當您在或ToStringVisual Basic Equals(Object)程式C#代碼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在或 Visual Basic 中C#撰寫的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. -物件的[](xref:System.Object.Equals*) 方法必須一致地傳回相同的雜湊碼,只要物件狀態沒有任何修改可判斷物件的system.object方法的傳回GetHashCode()值。- 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 字元的字串,但卻有string 可以包含任何 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.

適用於

另請參閱