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 會捨棄,因為這需要建立左的 shift 包裝方法如下所示: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 包裝方法來計算的雜湊碼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. (不相等的物件可以有相同的雜湊程式碼)。若要測試是否相等,呼叫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實作,以其中一個多載的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,它不會覆寫的類別提供的預設行為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 支援的 Windows 市集應用程式和 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. 不過,它們似乎具有ToStringEquals(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.

類別衍生自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.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 字元,即使的字串字串可以包含任何 65,535 的 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.

適用於

另請參閱