2017-03-11 16 views
0

下面的代碼是一個重面向對象的C#腳本,其中I接收到的錯誤的一部分:字典的containsKey後投擲StackOverflowException一個對象被稱爲

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

我發現這是特別奇怪,因爲我不能找不到任何可能與我的程序邏輯中無限發生的某種形式的過程有關的任何事情。

這將始終如一地發生爲operator !=我爲一個座標類,每當它被用來作爲應該已經返回true一個Dictionary.ContainsKey()參數的一部分。

這是協調課程:

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.

任何幫助將不勝感激。

回答

4

您正在重寫equals運算符(==)並在其中使用equals運算符。

a != null && b != null 

如果你想比較空,而無需使用您的運營商,要麼將其轉換爲對象首先,像(object)a != null或使用object.ReferenceEquals(a, null)

這也適用於您的不等於運營商,即使它沒有被Dictionary.ContainsKey使用。

+0

啊,這是有道理的。我忽略了我將參數座標視爲物體而不是獲取其組成部分的事實。非常感謝你! – Luke