共用方式為


CA2218:覆寫 Equals 時必須一併覆寫 GetHashCode

屬性
規則識別碼 CA2218
職稱 覆寫 Equals 時必須一併覆寫 GetHashCode
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 9 中啟用 建議

原因

公用型別會覆寫 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

另請參閱