CA1036:重写可比较类型中的方法
属性 | 值 |
---|---|
规则 ID | CA1036 |
标题 | 重写可比较类型中的方法 |
类别 | 设计 |
修复是中断修复还是非中断修复 | 非中断 |
在 .NET 8 中默认启用 | 否 |
原因
类型实现 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
相等运算符触发时,禁止显示此规则的警告也是安全的。 但是,如果重写Object.Equals,应始终重写op_Equality
运算符==
。
抑制警告
如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。
#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