CodeQL 文档

不一致的 Equals(object) 和 GetHashCode()

ID: cs/inconsistent-equals-and-gethashcode
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - reliability
   - maintainability
   - external/cwe/cwe-581
Query suites:
   - csharp-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

仅重写 Equals(object)GetHashCode() 中的一个的类很可能会违反 GetHashCode() 方法的协定。该协定要求 GetHashCode() 对于任意两个相等的对象都返回相同的整数结果。不强制执行此属性可能会在哈希数据结构中存储和检索此类类的对象时导致意外结果。

建议

提供与现有方法一致的缺失方法的实现。

示例

在以下示例中,类 Bad 重写了 Equals(object) 但没有重写 GetHashCode()

using System;

class Bad
{
    private int id;

    public Bad(int Id) { this.id = Id; }

    public override bool Equals(object other)
    {
        if (other is Bad b && b.GetType() == typeof(Bad))
            return this.id == b.id;
        return false;
    }
}

在修改后的示例中,类 Good 同时重写了 Equals(object)GetHashCode()

using System;

class Good
{
    private int id;

    public Good(int Id) { this.id = Id; }

    public override bool Equals(object other)
    {
        if (other is Good b && b.GetType() == typeof(Good))
            return this.id == b.id;
        return false;
    }

    public override int GetHashCode() => id;
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私