繁体   English   中英

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

[英]Dictionary throwing StackOverflowException after ContainsKey for an object is called

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

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

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

每当将它用作应返回trueDictionary.ContainsKey()的参数时,它将一直作为operator !=的一部分发生。

这是坐标类:

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'坐标operator !=(Coordinate a, Coordinate b)方法被列为“ Unable to read memory并且旁边有一个红色的X。 。

任何帮助将不胜感激。

您将覆盖equals运算符(==),并在其中使用equals运算符。

a != null && b != null

如果要比较null,则不使用运算符将​​其首先转换为对象,例如(object)a != null或使用object.ReferenceEquals(a, null)

这也适用于您的equals运算符,即使Dictionary.ContainsKey不使用它也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM