调用对象的 ContainsKey 后字典抛出 StackOverflowException

Dictionary throwing StackOverflowException after ContainsKey for an object is called

以下代码是面向对象的 C# 脚本的一部分,我在其中收到错误:

An unhandled exception of type 'System.WhosebugException' occurred in script.exe

我发现这特别奇怪,因为我找不到任何可能与我的程序逻辑中无限发生的某种形式的过程相关的东西。

它会一直作为我为坐标 class 制作的 operator != 的一部分发生,每当它被用作 Dictionary.ContainsKey() 的参数时应该返回 true.

这是坐标Class:

class Coordinate
{
    private int _x;
    private int _y;
    public int X
    {
        get
        {
            return _x;
        }
    }
    public int Y
    {
        get
        {
            return _y;
        }
    }

    public Coordinate(Random r)
    {
        this._x = r.Next(79);
        this._y = r.Next(24);
    }

    public Coordinate(int x, int y)
    {
        this._x = x;
        this._y = y;
    }

    public static Coordinate operator +(Coordinate a, Coordinate b)
    {
        return new Coordinate(a.X + b.X, a.Y + b.Y);
    }

    public static bool operator ==(Coordinate a, Coordinate b)
    {
        return ((a != null && b != null) && (a.X == b.X && a.Y == b.Y)) || (a == null && b == null);
    }

    public static bool operator !=(Coordinate a, Coordinate b)
    {
        return a != null && b != null && (a.X != b.X || a.Y != b.Y) || (a == null && b != null) || (a != null && b == null);
    }

    public override int GetHashCode()
    {
        return this.X.GetHashCode() * 23 + this.Y.GetHashCode() * 17;
    }

    public override bool Equals(object obj)
    {
        Coordinate other = obj as Coordinate;
        return other != null && other.X == this.X && other.Y == this.Y;
    }
}

每当 _positions.ContainsKey(position) 应该返回 true:

时,这就是始终导致错误的代码
private bool OutOfRangeCheck(Coordinate position)
{
    return position.X < 1 || position.X > 10 || position.Y < 1 || position.Y > 10;
}

private bool PositionConflictCheck(Coordinate position)
{
    bool temp = _positions.ContainsKey(position);
    return OutOfRangeCheck(position) || _positions.ContainsKey(position);
}

这部分程序的目标是查看特定坐标是否在所示字典中具有对应的 X 和 Y 值。我发现除非我重写了 GetHashCode()Equals() 方法,否则这是行不通的。

如果有帮助,在抛出错误时查看局部变量时,operator !=(Coordinate a, Coordinate b) 方法中的 'a' 坐标被列为 Unable to read memory 并且有一个红色的 X旁边。

如有任何帮助,我们将不胜感激。

您正在覆盖等号运算符 (==) 并在其中使用等号运算符。

a != null && b != null

如果你想与 null 进行比较,而不使用你的运算符,要么先将它转换为一个对象,比如 (object)a != null,要么使用 object.ReferenceEquals(a, null).

这也适用于您的不等于运算符,即使 Dictionary.ContainsKey 没有使用它。