gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:49:39 26 4
gpt4 key购买 nike

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

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

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

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

这是坐标类:

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 !=(坐标 a, 坐标 b) 方法中的“a”坐标被列为 无法读取内存并且旁边有一个红色的X。

任何帮助将不胜感激。

最佳答案

您正在重写等于运算符 (==) 并在其中使用等于运算符。

a != null && b != null

如果您想与 null 进行比较,而不使用运算符,请先将其转换为对象,例如 (object)a != null 或使用 object.ReferenceEquals(a,空)

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

关于c# - 调用对象的 ContainsKey 后字典抛出 StackOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com