在调用对象的ContainsKey之后调用StackOverflowException字典

时间:2017-03-11 22:03:22

标签: c# class dictionary stack-overflow

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

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

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

它会一直作为我为Coordinates类所做的operator !=的一部分而发生,只要它被用作应该返回Dictionary.ContainsKey()的{​​{1}}的参数。

这是坐标类:

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

该程序的这一部分的目标是查看特定的Coordinate是否在所显示的字典中具有相等的X和Y值的对应物。我发现除非我覆盖了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); } GetHashCode()方法,否则这不会起作用。

如果有帮助,当查看错误被抛出时的局部变量时,&#39; a&#39; Equals()方法中的坐标列为operator !=(Coordinate a, Coordinate b),旁边有一个红色的X.

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

您正在覆盖equals运算符(==)并在那里使用equals运算符。

a != null && b != null

如果您想要与null进行比较,请不要使用您的操作符,先将其强制转换为对象,例如(object)a != null或使用object.ReferenceEquals(a, null)

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

相关问题