CodeQL 文档

Equals(object) 的空参数

ID: cs/null-argument-to-equals
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - reliability
   - correctness
Query suites:
   - csharp-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

通常需要对照 null 检查对象,但不应使用 Equals 方法执行此操作。如果对象确实为 null,则在尝试调用 Equals 时会引发 NullReferenceException,从而导致意外结果。

建议

应将违规调用替换为 ==ReferenceEquals(区别在于可以重写 ==,但不能重写 ReferenceEquals)。

示例

在以下示例中,当 onull 时,IsNull 将引发 NullReferenceException

class Bad
{
    bool IsNull(object o) => o.Equals(null);
}

在修改后的示例中,当 onull 时,IsNull 将正确返回 true

class Good
{
    bool IsNull(object o) => o == null;
}

参考

  • ©GitHub 公司
  • 条款
  • 隐私