C# 如何在等式上比较多维数组?

C# 如何在等式上比较多维数组?,c#,multidimensional-array,compare,equals,C#,Multidimensional Array,Compare,Equals,我知道你可以用它来检查平等性。但是多维数组没有这样的方法。关于如何比较二维数组有什么建议吗 实际问题: public class SudokuGrid { public Field[,] Grid { get { return grid; } private set { grid = value; } } } public class Field { private byte digit; private bool isR

我知道你可以用它来检查平等性。但是多维数组没有这样的方法。关于如何比较二维数组有什么建议吗

实际问题:

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个网格的值,而不是它们的引用

因为我通过构造函数使用私有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 expected = new SudokuGrid(2, 3);
但应该是:

Field[,] expected = sudoku.Grid;
所以我不能用这个类来比较它的网格属性,因为我不能只设置网格,因为setter是私有的。 如果我不得不改变我的原始代码以便我的单元测试可以工作,那将是愚蠢的

问题:

  • 那么,它们是比较多维数组的一种方法吗?(那么我可以重写多维数组使用的相等方法吗?)
  • 有没有别的办法解决我的问题
您可以使用以下扩展方法,但必须使
字段
实现
可比较

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;
}
publicstaticboolcontentequals(这个T[,]arr,T[,]other),其中T:IComparable
{
如果(arr.GetLength(0)!=其他.GetLength(0)||
arr.GetLength(1)!=其他.GetLength(1))
返回false;
for(int i=0;i
您的问题并不完全清楚。但是,为什么不使用索引器删除网格的嵌套;i、 e.
公共字段这个[intx,inty]{get;set;}
在SudokuGrid中;因此,SudokuGrid有效地隐藏了实际的数组,并提供了改变电路板的机制;现在您可以测试这些功能是否正常工作;只要对两个对象的相同操作产生相同的结果,我就看不出有什么问题。我通过在代码中添加工厂模式来解决这个问题。所以我在我的工厂方法中填充我的数独,并在那里公开我的所有方法。不完全是我想要的,但我想我没有其他选择。
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;
}