【问题标题】:How to compare multidimensional arrays on equality?如何比较多维数组是否相等?
【发布时间】:2013-03-14 16:25:02
【问题描述】:

我知道你可以使用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 构造函数中设置。所以所有这些属性都有 private 设置器。我想保持这种状态。

现在,我正在使用 C# 单元测试进行一些测试。我想比较 2 Grids 的值而不是它们的引用。

因为我通过构造函数使用私有设置器设置了所有内容。 SudokuGrid 类中的这个 Equal 覆盖是正确的,但不是我需要的:

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 是私有的。 如果我不得不更改我的原始代码以便我的单元测试可以工作,那将是愚蠢的。

问题:

  • 那么它们是一种实际比较多维数组的方法吗? (那么我可以覆盖多维数组使用的 equal 方法吗?)
  • 是否有其他方法可以解决我的问题?

【问题讨论】:

  • 不完全清楚你的问题是什么。但是,为什么不使用索引器删除 Grid 的嵌套呢?即 SudokuGrid 中的 public Field this[int x, int y]{get;set;};所以 SudokuGrid 有效地隐藏了实际的数组并提供了改变棋盘的机制;现在您可以测试这些功能是否正常工作;只要对两个对象进行相同的操作会产生 Equal 结果,我看不出有问题。
  • 好吧,我通过在我的代码中添加工厂模式来修复它。所以我在我的工厂方法中填写了我的数独,并将我的所有方法公开。不完全是我想要的,但我想我没有其他选择。

标签: c# multidimensional-array compare equals


【解决方案1】:

你可以使用下面的扩展方法,但是你必须让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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    相关资源
    最近更新 更多