CA2218:重写 Equals 时重写 GetHashCode
属性 | 值 |
---|---|
规则 ID | 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 时应重载相等运算符