Luk*_*uke 2 c# stack-overflow dictionary class
以下代码是大量面向对象的 C# 脚本的一部分,在那里我收到了错误:
An unhandled exception of type 'System.StackOverflowException' occurred in script.exe
Run Code Online (Sandbox Code Playgroud)
我发现这特别奇怪,因为我找不到任何可能与我的程序逻辑中无限发生的某种形式的过程有关的任何东西。
它会一直发生作为operator !=我为 Coordinates 类制作的一部分,每当它被用作Dictionary.ContainsKey()应该返回的a 的参数时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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是始终会导致错误的代码,无论何时_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);
}
Run Code Online (Sandbox Code Playgroud)
这部分程序的目标是查看特定坐标是否在显示的字典中具有相等的 X 和 Y 值的对应项。我发现除非我覆盖了GetHashCode()和Equals()方法,否则这将不起作用。
如果有帮助,当在抛出错误时查看局部变量时,方法中的“a”坐标operator !=(Coordinate a, Coordinate b)被列为Unable to read memory并在其旁边有一个红色的 X。
任何帮助将不胜感激。
您正在覆盖等于运算符 (==) 并在其中使用等于运算符。
a != null && b != null
Run Code Online (Sandbox Code Playgroud)
如果您想与 null 进行比较,而不使用您的运算符,请先将其转换为对象,例如(object)a != null或使用object.ReferenceEquals(a, null).
这也适用于您的不等于运算符,即使Dictionary.ContainsKey.