CA2224:重载相等运算符时重写 Equals 方法

属性
规则 ID CA2224
标题 重载相等运算符时重写 Equals 方法
类别 使用情况
修复是中断修复还是非中断修复 非中断
在 .NET 9 中默认启用 作为建议

原因

公共类型会实现相等运算符,但不重写 System.Object.Equals

规则说明

相等运算符旨在以语法上方便的方式访问 Equals 方法的功能。 如果实现相等运算符,其逻辑与 Equals 的逻辑必须相同。

注意

此规则仅适用于 Visual Basic 代码。 C# 编译器生成单独的警告 CS0660

如何解决冲突

若要解决与此规则的冲突,应删除相等运算符的实现,或重写 Equals 并使两个方法返回相同的值。 如果相等运算符未引入不一致的行为,则可以提供可调用基类中 Equals 方法的 Equals 的实现来解决冲突。

何时禁止显示警告

如果相等运算符返回的值与继承的 Equals 实现的值相同,则可以安全地禁止显示此规则发出的警告。 本文中的示例包括一个可安全地禁止显示此规则发出的警告的类型。

抑制警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

#pragma warning disable CA2224
// The code that's violating the rule is on this line.
#pragma warning restore CA2224

若要对文件、文件夹或项目禁用该规则,请在配置文件中将其严重性设置为 none

[*.{cs,vb}]
dotnet_diagnostic.CA2224.severity = none

有关详细信息,请参阅如何禁止显示代码分析警告

示例

下面的示例显示了一个与此规则冲突的类(引用类型)。

' 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 GetHashCode() As Integer
        Return HashCode.Combine(X, Y)
    End Function

    Public Shared Operator =(pt1 As Point, pt2 As Point) As Boolean
        If pt1 Is Nothing OrElse pt2 Is Nothing Then
            Return False
        End If

        If pt1.GetType() <> pt2.GetType() Then
            Return False
        End If

        Return pt1.X = pt2.X AndAlso pt1.Y = pt2.Y
    End Operator

    Public Shared Operator <>(pt1 As Point, pt2 As Point) As Boolean
        Return Not pt1 = pt2
    End Operator

End Class

下面的示例通过重写 System.Object.Equals 来解决冲突。

' 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 HashCode.Combine(X, 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 X = pt.X AndAlso Y = pt.Y

    End Function

    Public Shared Operator =(pt1 As Point, pt2 As Point) As Boolean
        ' Object.Equals calls Point.Equals(Object).
        Return Object.Equals(pt1, pt2)
    End Operator

    Public Shared Operator <>(pt1 As Point, pt2 As Point) As Boolean
        ' Object.Equals calls Point.Equals(Object).
        Return Not Object.Equals(pt1, pt2)
    End Operator

End Class

另请参阅