CA1066:覆寫 Equals 時實作 IEquatable

屬性
規則識別碼 CA1066
標題 覆寫 Equals 時實作 IEquatable
類別 設計
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

實值型別 (結構) 會 Equals 覆寫 方法,但不會實作 IEquatable<T>

檔案描述

實值型別覆寫 Equals 方法表示它支持比較類型兩個實例的值相等。 請考慮實作 IEquatable<T> 介面,以支持強型別測試是否相等。 這可確保執行相等檢查的呼叫端會叫用強型別 System.IEquatable<T>.Equals 方法,並避免將自變數進行 Boxing,以改善效能。 如需詳細資訊,請參閱此處

您的 System.IEquatable<T>.Equals 實作應該會傳回與 Equals一致的結果。

如何修正違規

若要修正違規,請實 IEquatable<T> 作和更新 Equals 覆寫以叫用這個實作的方法。 例如,下列兩個代碼段會顯示違反規則,以及如何修正它:

public struct S
{
    private readonly int _value;
    public S(int f)
    {
        _value = f;
    }

    public override int GetHashCode()
        => _value.GetHashCode();

    public override bool Equals(object other)
        => other is S otherS && _value == otherS._value;
}
using System;

public struct S : IEquatable<S>
{
    private readonly int _value;
    public S(int f)
    {
        _value = f;
    }

    public override int GetHashCode()
        => _value.GetHashCode();

    public override bool Equals(object other)
        => other is S otherS && Equals(otherS);

    public bool Equals(S other)
        => _value == other._value;
}

隱藏警告的時機

如果實作介面的設計和效能優點並不重要,則隱藏此規則的違規是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

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

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

另請參閱