| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA2218 |
| Title | 覆寫 Equals 時必須一併覆寫 GetHashCode |
| Category | Usage |
| 修正是破壞性或非破壞性 | 不間斷 |
| 預設啟用於 .NET 10 版本 | 建議 |
| 在 .NET 11 中預設啟用 | 建議 |
| 適用語言 | Visual Basic |
原因
公用類別會覆寫 System.Object.Equals,但不會覆寫 System.Object.GetHashCode。
規則描述
GetHashCode 回傳一個基於目前實例的值,適用於雜湊演算法及資料結構(如雜湊表)。 兩個具有相同類型且相等的物件必須傳回相同的雜湊碼,以確保下列類型的執行個體正常運作:
- System.Collections.Hashtable
- System.Collections.SortedList
- System.Collections.Generic.Dictionary<TKey,TValue>
- System.Collections.Generic.SortedDictionary<TKey,TValue>
- System.Collections.Generic.SortedList<TKey,TValue>
- System.Collections.Specialized.HybridDictionary
- System.Collections.Specialized.ListDictionary
- System.Collections.Specialized.OrderedDictionary
- 實作 System.Collections.Generic.IEqualityComparer<T> 的類型
注意
此規則僅適用於 Visual Basic 程式代碼。 C# 編譯程式會產生個別的警告 CS0659。
如何修正違規
若要修正違反此規則的情況,請提供 GetHashCode 的實作。 如果針對相同型別的物件組合,您的 Equals 實作為該組合傳回 true,請確保實作會為該組合返回相同的值。
隱藏警告的時機
請勿隱藏此規則的警告。
類別範例
下列範例顯示違反此規則的類別 (參考型別)。
' This class violates the rule.
Public Class Point
Public Property X As Integer
Public Property 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 obj = Nothing Then
Return False
End If
If [GetType]() <> obj.GetType() Then
Return False
End If
Dim pt As Point = CType(obj, Point)
Return X = pt.X AndAlso Y = pt.Y
End Function
End Class
下列範例藉由覆寫 GetHashCode() 來修正違規行為。
' This class satisfies the rule.
Public Class Point
Public Property X As Integer
Public Property Y As Integer
Public Sub New(x As Integer, y As Integer)
Me.X = x
Me.Y = y
End Sub
Public Overrides Function GetHashCode() As Integer
Return X Or Y
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj = Nothing Then
Return False
End If
If [GetType]() <> obj.GetType() Then
Return False
End If
Dim pt As Point = CType(obj, Point)
Return Equals(pt)
End Function
Public Overloads Function Equals(pt As Point) As Boolean
Return X = pt.X AndAlso Y = pt.Y
End Function
Public Shared Operator =(pt1 As Point, pt2 As Point) As Boolean
Return pt1.Equals(pt2)
End Operator
Public Shared Operator <>(pt1 As Point, pt2 As Point) As Boolean
Return Not pt1.Equals(pt2)
End Operator
End Class
相關規則
- CA1046:不要在參考型別上多載等於運算子
- CA2224:多載等號運算子時,請覆寫 Equals
- CA2225:運算子多載具有具名替代項
- CA2226:運算子應具有對稱的多載
- CA2231:覆寫 ValueType.Equals 時,多載等號運算子