共用方式為


CA2224:覆寫多載運算符相等的 Equals

屬性
規則識別碼 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

另請參閱