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

傳回

Int32

目前物件的雜湊碼。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. 下列範例顯示結構的這類執行 NumberThe 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)
        {
            Point p = (Point) obj;
            return x == p.x & y == p.y;
        }
        else
        {
            return false;
        }      
    }

    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. 最理想的情況是,超過 bit 31 的位會換行,而不是捨棄。Optimally, bits shifted beyond bit 31 should wrap around rather than be discarded. 由於 c # 和 Visual Basic 中的左移運算子會捨棄位,因此需要建立左移和換行方法,如下所示: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

下列範例會使用這個移位和換行方法來計算先前範例中所使用之結構的雜湊碼 PointThe 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 類別或衍生自類別的型別 DictionaryBaseA 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. (不相等的物件可以有相同的雜湊碼。 ) 若要測試是否相等,請呼叫 ReferenceEqualsEquals 方法。(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 值,您可以藉由提供實值給類別的函式的 IEqualityComparer 其中一個多載,指定雜湊碼提供者 HashtableIf 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 ,它會為不會覆寫的類別提供預設行為 GetHashCodeWhen 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 請參閱 .NET Framework Microsoft Store 應用程式的支援和 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 ,而且目前不會執行 GetHashCodeClasses in the Windows 執行階段Windows Runtime don't inherit Object, and currently don't implement a GetHashCode. 但是, ToString Equals(Object) GetHashCode 當您在 c # 或 Visual Basic 程式碼中使用這些方法時,它們看起來會有、和方法,而 .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.

針對衍生自的類別 ObjectGetHashCode 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. 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 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.

適用於

另請參閱