2013-03-14 27 views
5

我知道你可以使用Enumerable.SequenceEqual來檢查平等。但是多維數組沒有這種方法。 有關如何比較二維數組的任何建議?如何比較多維數組上的平等?

實際的問題:

public class SudokuGrid 
{ 
    public Field[,] Grid 
    { 
     get { return grid; } 
     private set { grid = value; } 
    } 
} 

public class Field 
{ 
    private byte digit; 
    private bool isReadOnly; 
    private Coordinate coordinate; 
    private Field previousField; 
    private Field nextField; 
} 

所有這些屬性在SudokuGrid構造方法設置。所以所有這些屬性都有專用設置者。我想保持這種方式。

現在,我正在用C#單元測試進行一些測試。我想比較2 Grids對他們的價值,而不是他們的參考。

因爲我通過構造函數設置私人setter的一切。在SudokuGrid類這等於重寫是正確的,但不是我所需要的:

public bool Equals(SudokuGrid other) 
{ 
    if ((object)other == null) return false; 

    bool isEqual = true; 

    for (byte x = 0; x < this.Grid.GetLength(0); x++) // 0 represents the 1st dimensional array 
    { 
     for (byte y = 0; y < this.Grid.GetLength(1); y++) // 1 represents the 2nd dimensional array 
     { 
      if (!this.Grid[x, y].Equals(other.Grid[x, y])) 
      { 
       isEqual = false; 
      } 
     } 
    } 

    return isEqual; 
} 

這不是我所需要的,因爲我在做測試。所以,如果我的實際數獨是:

SudokuGrid actual = new SudokuGrid(2, 3); 

那麼我預計數獨不能只是:

SudokuGrid expected = new SudokuGrid(2, 3); 

,但應該是:

Field[,] expected = sudoku.Grid; 

所以我不能使用類比較它的網格屬性,因爲我不能只設置網格,因爲setter是私人的。 如果我不得不更改我的原始代碼,那麼我的單元測試就可以工作,這將是愚蠢的。

問題:

  • 所以是他們的方式來實際比較多維數組? (所以我可能會覆蓋多維陣列使用的平等方法?)
  • 是否有另一種方法可以解決我的問題?
+0

它並不完全清楚你的問題是什麼。但是,爲什麼不用一個索引器去除網格的嵌套;即在SudokuGrid中的'public Field this [int x,int y] {get; set;}';所以SudokuGrid有效地隱藏了實際的數組並提供了改變棋盤的機制;現在您可以測試這些功能是否正常工作;只要對兩個對象執行相同的操作會得到相等的結果,我就不會看到問題。 – 2013-03-14 16:38:32

+0

好吧,我通過給我的代碼添加一個工廠模式來修復它。所以我用我的工廠方法填充我的數獨,並將我的所有方法都公諸於衆。不完全是我想要的,但猜測我沒有任何其他選擇。 – dylanmensaert 2013-03-14 17:41:04

+0

[請勿將meta標籤放在標題中](http://meta.stackexchange.com/q/19190/135230) – 2013-03-14 18:33:21

回答

2

您可以使用下面的擴展方法,但你將不得不作出Field實施IComparable

public static bool ContentEquals<T>(this T[,] arr, T[,] other) where T : IComparable 
{ 
    if (arr.GetLength(0) != other.GetLength(0) || 
     arr.GetLength(1) != other.GetLength(1)) 
     return false; 
    for (int i = 0; i < arr.GetLength(0); i++) 
     for (int j = 0; j < arr.GetLength(1); j++) 
      if (arr[i, j].CompareTo(other[i, j]) != 0) 
       return false; 
    return true; 
}