CodeQL 文档

未定义 GetHashCode 的哈希值

ID: cs/gethashcode-is-not-defined
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - reliability
   - maintainability
Query suites:
   - csharp-security-and-quality.qls

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

如果将重写 System.Object.Equals() 但未重写 System.Object.GetHashCode() 的类的实例存储在哈希数据结构中,则可能会产生意外结果。

建议

重写 GetHashCode 方法,以便对于两个实例 a 和 b,如果 a.Equals(b) 为 true,则 a.GetHashCode() 和 b.GetHashCode() 相等。C# 文档指出 [1]

如果两个对象比较相等,则每个对象的 GetHashCode 方法必须返回相同的值。但是,如果两个对象比较不相等,则这两个对象的 GetHashCode 方法不必返回不同的值。

示例

using System;
using System.Collections;

class Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(Object other)
    {
        Point point = other as Point;
        if (point == null)
        {
            return false;
        }
        return this.x == point.x && this.y == point.y;
    }

    public static void Main(string[] args)
    {
        Hashtable hashtable = new Hashtable();
        hashtable[new Point(5, 4)] = "A point"; // BAD
        // Point overrides the Equals method but not GetHashCode.
        // As such it is probably not useful to use one as the key for a Hashtable.
        Console.WriteLine(hashtable[new Point(5, 4)]);
    }
}

参考

  • ©GitHub 公司
  • 条款
  • 隐私