CA2218:覆寫 Equals 時必須一併覆寫 GetHashCode
屬性 | 值 |
---|---|
規則識別碼 | CA2218 |
標題 | 覆寫 Equals 時必須一併覆寫 GetHashCode |
類別 | 使用方式 |
修正程式是中斷或非中斷 | 不中斷 |
預設在 .NET 8 中啟用 | 建議 |
原因
公用型別會覆寫 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 上多載等號運算子