我有一个多维数组,我将其用作盒子,并且我有一些在其周围生成边框的代码,如下所示:

#######
#     #
#     #
#     #
#     #
#######


但是,我不明白的是,在“ j == ProcArea.GetUpperBound(...)”部分中可以有0或1,并且它可以成功运行而没有任何错误或意外输出。

            int[,] ProcArea = new int[rows, columns];
            //Generate border
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    if (i == 0 || j == 0 || i == ProcArea.GetUpperBound(0) || j == ProcArea.GetUpperBound(1))
                    {
                        ProcArea[i, j] = 2;

                    }
                }
            }


为什么这样做有效,我应该使用什么正确的值?

谢谢

最佳答案

如果行数和列数相同,则GetUpperBound(0)GetUpperBound(1)将返回相同的值。

在C#中创建的数组(除非直接调用Array.CreateInstance)始终基于0。因此,GetUpperBound(0)将始终返回rows - 1,而GetUpperBound(1)将始终返回columns - 1

因此,无论您检查哪个上限,代码都将“起作用”,尽管我认为您会发现,如果使用rows != columns,则使用GetUpperBound(0)会创建与GetUpperBound(1)不同的大小框。

顺便说一句,制作边框的另一种方法是:

var maxRow = ProcArea.GetUpperBound(0);
var maxCol = ProcArea.GetUpperBound(1);
// do top and bottom
for (int col = 0; col <= maxCol; ++col)
{
    ProcArea[0, col] = 2;
    ProcArea[maxRow, col] = 2;
}
// do left and right
for (int row = 0; row <= maxRow; ++row)
{
    ProcArea[row, 0] = 2;
    ProcArea[row, maxCol] = 2;
}


确实,这是更多的代码,但是您不必浪费时间检查索引。当然,使用小数组不会有所作为。

关于c# - C#在2D阵列周围打印边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17884753/

10-11 22:00