CA2218:重写 Equals 时重写 GetHashCode

属性
规则 ID CA2218
标题 重写 Equals 时重写 GetHashCode
类别 使用情况
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用 作为建议

原因

公共类型重写 System.Object.Equals,但不重写 System.Object.GetHashCode

规则说明

GetHashCode 基于当前实例返回一个适合哈希算法和哈希表之类的数据结构的值。 两个相同类型且相等的对象必须返回相同的哈希代码,以确保以下类型的实例正常工作:

注意

此规则仅适用于 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

另请参阅