CA1036:必須在 Comparable 類型中覆寫方法
屬性 | 值 |
---|---|
規則識別碼 | CA1036 |
職稱 | 必須在 Comparable 類型中覆寫方法 |
類別 | 設計 |
修正程式是中斷或非中斷 | 不中斷 |
預設在 .NET 9 中啟用 | No |
原因
類型會實作 System.IComparable 介面,且不會覆寫 System.Object.Equals 或未多載語言特定運算符,以取得相等、不相等、小於或大於。 如果型別只繼承介面的實作,規則不會報告違規。
根據預設,此規則只會查看外部可見的類型,但這是可設定的。
檔案描述
定義自定義排序順序的類型會實作 IComparable 介面。 方法 CompareTo 會傳回整數值,指出型別兩個實例的正確排序順序。 此規則會識別設定排序順序的類型。 設定排序順序表示相等、不相等、小於和大於的一般意義不適用。 當您提供的 IComparable實作時,通常也必須覆寫 Equals ,使其傳回與 CompareTo一致的值。 如果您以支援運算子多載的語言覆寫 Equals 和撰寫程式代碼,則也應該提供與 Equals一致的運算符。
如何修正違規
若要修正此規則的違規,請覆寫 Equals。 如果您的程式設計語言支援運算子多載,請提供下列運算子:
op_Equality
op_Inequality
op_LessThan
op_GreaterThan
// In C#, implement these operators.
public static bool operator ==(SampleClass? one, SampleClass? other) { }
public static bool operator !=(SampleClass? one, SampleClass? other) { }
public static bool operator <(SampleClass? one, SampleClass? other) { }
public static bool operator >(SampleClass? one, SampleClass? other) { }
' In Visual Basic, implement these operators.
Public Shared Operator =(one As SampleClass, other As SampleClass) As Boolean
...
End Operator
Public Shared Operator <>(one As SampleClass, other As SampleClass) As Boolean
...
End Operator
Public Shared Operator <(one As SampleClass, other As SampleClass) As Boolean
...
End Operator
Public Shared Operator >(one As SampleClass, other As SampleClass) As Boolean
...
End Operator
隱藏警告的時機
當違規是由遺漏運算符所造成,且您的程式設計語言不支援運算元多載時,隱藏來自規則 CA1036 的警告是安全的。 如果您判斷在應用程式內容中實作運算符並無意義,在對 以外的 op_Equality
等號運算符引發時,隱藏此規則的警告也是安全的。 不過,如果您覆寫 ,則應該一律覆寫 op_Equality
Object.Equals和 ==
運算符。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA1036
// The code that's violating the rule is on this line.
#pragma warning restore CA1036
若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none
[*.{cs,vb}]
dotnet_diagnostic.CA1036.severity = none
如需詳細資訊,請參閱 如何隱藏程式代碼分析警告。
設定程式代碼以分析
使用下列選項來設定程式代碼基底要執行此規則的部分。
您可以只針對此規則、針對它套用的所有規則,或針對套用至此類別的所有規則,或針對它套用的所有規則,設定此選項。 如需詳細資訊,請參閱 程式代碼品質規則組態選項。
包含特定 API 介面
您可以根據程式代碼基底的存取範圍,設定要執行此規則的部分。 例如,若要指定規則只應該針對非公用 API 介面執行,請將下列機碼/值組新增至 專案中的 .editorconfig 檔案:
dotnet_code_quality.CAXXXX.api_surface = private, internal
範例
下列程式代碼包含可正確實作 IComparable的型別。 程序代碼批注會識別滿足與 Equals 和 IComparable 介面相關之各種規則的方法。
// Valid ratings are between A and C.
// A is the highest rating; it is greater than any other valid rating.
// C is the lowest rating; it is less than any other valid rating.
public class RatingInformation : IComparable, IComparable<RatingInformation>
{
public string Rating { get; private set; }
public RatingInformation(string rating)
{
ArgumentNullException.ThrowIfNull(rating);
string v = rating.ToUpper(CultureInfo.InvariantCulture);
if (v.Length != 1 ||
string.Compare(v, "C", StringComparison.Ordinal) > 0 ||
string.Compare(v, "A", StringComparison.Ordinal) < 0)
{
throw new ArgumentException("Invalid rating value was specified.", nameof(rating));
}
Rating = v;
}
public int CompareTo(object? obj)
{
if (obj == null)
{
return 1;
}
if (obj is RatingInformation other)
{
return CompareTo(other);
}
throw new ArgumentException("A RatingInformation object is required for comparison.", nameof(obj));
}
public int CompareTo(RatingInformation? other)
{
if (other is null)
{
return 1;
}
// Ratings compare opposite to normal string order,
// so reverse the value returned by String.CompareTo.
return -string.Compare(Rating, other.Rating, StringComparison.OrdinalIgnoreCase);
}
public static int Compare(RatingInformation left, RatingInformation right)
{
if (object.ReferenceEquals(left, right))
{
return 0;
}
if (left is null)
{
return -1;
}
return left.CompareTo(right);
}
// Omitting Equals violates rule: OverrideMethodsOnComparableTypes.
public override bool Equals(object? obj)
{
if (obj is RatingInformation other)
{
return CompareTo(other) == 0;
}
return false;
}
// Omitting getHashCode violates rule: OverrideGetHashCodeOnOverridingEquals.
public override int GetHashCode()
{
char[] c = Rating.ToCharArray();
return (int)c[0];
}
// Omitting any of the following operator overloads
// violates rule: OverrideMethodsOnComparableTypes.
public static bool operator ==(RatingInformation left, RatingInformation right)
{
if (left is null)
{
return right is null;
}
return left.Equals(right);
}
public static bool operator !=(RatingInformation left, RatingInformation right)
{
return !(left == right);
}
public static bool operator <(RatingInformation left, RatingInformation right)
{
return (Compare(left, right) < 0);
}
public static bool operator >(RatingInformation left, RatingInformation right)
{
return (Compare(left, right) > 0);
}
}
Imports System.Globalization
Public Class RatingInformation
Implements IComparable
Implements IComparable(Of RatingInformation)
Public Sub New(rating As String)
ArgumentNullException.ThrowIfNull(rating)
Dim v As String = rating.ToUpper(CultureInfo.InvariantCulture)
If (v.Length <> 1 Or
String.Compare(v, "C", StringComparison.Ordinal) > 0 Or
String.Compare(v, "A", StringComparison.Ordinal) < 0) Then
Throw New ArgumentException("Invalid rating value was specified.", NameOf(rating))
End If
Me.Rating = v
End Sub
Public ReadOnly Property Rating As String
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
If (obj Is Nothing) Then Return 1
If (TypeOf obj IsNot RatingInformation) Then Return 0
Dim other As RatingInformation = DirectCast(obj, RatingInformation)
Return CompareTo(other)
End Function
Public Function CompareTo(other As RatingInformation) As Integer Implements IComparable(Of RatingInformation).CompareTo
If (other Is Nothing) Then Return 1
' Ratings compare opposite To normal String order,
' so reverse the value returned by String.CompareTo.
Return -String.Compare(Rating, other.Rating, StringComparison.OrdinalIgnoreCase)
End Function
Public Shared Operator =(one As RatingInformation, other As RatingInformation) As Boolean
If (one Is Nothing) Then Return (other Is Nothing)
If (other Is Nothing) Then Return False
Return (one.Rating = other.Rating)
End Operator
Public Shared Operator <>(one As RatingInformation, other As RatingInformation) As Boolean
If (one Is Nothing) Then Return (other IsNot Nothing)
If (other Is Nothing) Then Return True
Return (one.Rating <> other.Rating)
End Operator
Public Shared Operator <(one As RatingInformation, other As RatingInformation) As Boolean
If (one Is Nothing) Then Return (other IsNot Nothing)
If (other Is Nothing) Then Return False
Return (one.Rating < other.Rating)
End Operator
Public Shared Operator >(one As RatingInformation, other As RatingInformation) As Boolean
If (one Is Nothing) Then Return False
If (other Is Nothing) Then Return True
Return (one.Rating > other.Rating)
End Operator
Public Overrides Function Equals(obj As Object) As Boolean
If ReferenceEquals(Me, obj) Then
Return True
End If
If obj Is Nothing Then
Return False
End If
Throw New NotImplementedException()
End Function
Public Overrides Function GetHashCode() As Integer
Throw New NotImplementedException()
End Function
End Class
下列應用程式程式代碼會測試稍早所顯示實作 IComparable 的行為。
public class TestCompare
{
public static void Main1036(params string[] args)
{
if (args.Length < 2)
{
return;
}
RatingInformation r1 = new(args[0]);
RatingInformation r2 = new(args[1]);
string answer;
if (r1.CompareTo(r2) > 0)
answer = "greater than";
else if (r1.CompareTo(r2) < 0)
answer = "less than";
else
answer = "equal to";
Console.WriteLine("{0} is {1} {2}", r1.Rating, answer, r2.Rating);
}
}
Public Class TestCompare
Public Shared Sub Main1036(ByVal args As String())
If (args.Length < 2) Then
Return
End If
Dim r1 As New RatingInformation(args(0))
Dim r2 As New RatingInformation(args(1))
Dim answer As String
If (r1.CompareTo(r2) > 0) Then
answer = "greater than"
ElseIf (r1.CompareTo(r2) < 0) Then
answer = "less than"
Else
answer = "equal to"
End If
Console.WriteLine("{0} is {1} {2}", r1.Rating, answer, r2.Rating)
End Sub
End Class