可能错误的 Equals(...) 签名¶
ID: cs/wrong-equals-signature
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- reliability
- maintainability
Query suites:
- csharp-security-and-quality.qls
在类上定义 Equals(object)
方法的目的是为了确保在客户端代码和库代码中都使用该方法来比较该类的实例。标准 Equals(object)
方法具有 object
参数,因此 Equals(T)
方法(其中 T
不是 object
)通常不会被使用,而是使用 Equals(object)
。
建议¶
定义一个 Equals(object)
方法,如果 object 参数不是包含该方法的类型,则返回 false。
示例¶
在此示例中,Equals
方法仅接受 Bad
的实例作为参数。
using System;
class Bad
{
private int id;
public Bad(int Id)
{
this.id = Id;
}
public bool Equals(Bad b) =>
this.id == b.id;
}
在修改后的示例中,Equals(object)
被重写,并根据 Equals(Good)
方法进行定义。
using System;
class Good
{
private int id;
public Good(int Id)
{
this.id = Id;
}
public bool Equals(Good g) =>
this.id == g.id;
public override bool Equals(object o)
{
if (o is Good g && g.GetType() == typeof(Good))
return this.Equals(g);
return false;
}
}