不显示锯齿状数组

Jagged array is not displayed

我在玩锯齿状数组,我在 him.I 中创建了一个带有 3 个二维数组的一维整数锯齿状数组,想显示我的锯齿状数组,但是当我 运行 代码时,我get Exception Unhandled.It writes that index of my elements in array get out of range.I 认为在确定计数器中的数组长度时有问题,即计数器应该多长的问题计数。

int[][,] a = new int[3][,] {
    new int[,]{ { 1,2},{ 3,4}},
    new int[,]{ {65,10 },{7,8 }},
    new int[,]{{5,6},{86,31}, }
};
for(int i = 0; i <a[i].Length; i++)
{
    Console.WriteLine("{0}.tabel",(i+1));

    for(int k = 0; k < a[k].Length; k++)
    {    //*This is the place where I get an exception
         Console.Write(a[i][i,k]);
    }
}

我的目标是使程序输出如下所示:

1. tabel
1 2
3 4
2. tabel
65 10
7 8
3. tabel
5 6
86 31

P.S。我在未处理异常的地方写评论 有人可以帮助我吗?

因为你有 3 个维度,所以你需要 3 个嵌套循环。另外,如果数组有多个维度,则必须使用 GetLenth(dimension) 并指定维度编号(基于 0):

int[][,] a = new int[3][,] {
    new int[,] { { 1, 2 }, { 3, 4 } },
    new int[,] { { 65, 10 }, { 7, 8 } },
    new int[,] { { 5, 6 }, { 86, 31 }, }
};
for (int i = 0; i < a.Length; i++) { // Loop over a[i]
    Console.WriteLine($"{i + 1}. tabel");
    for (int j = 0; j < a[i].GetLength(0); j++) { // Loop over a[][j,]
        Console.Write("   ");
        for (int k = 0; k < a[i].GetLength(1); k++) { // Loop over a[][,k]
            Console.Write($" {a[i][j, k]}");
        }
        Console.WriteLine();
    }
}

a[i].Length 对于 [n, m] 大小的数组产生 n * m.

如果将内部数组分配给局部变量,它会变得更加清晰:

for (int i = 0; i < a.Length; i++) { // Loop over a[i]
    Console.WriteLine($"{i + 1}. tabel");
    int[,] matrix = a[i];
    for (int j = 0; j < matrix.GetLength(0); j++) { // Loop over matrix[j,]
        Console.Write("  ");
        for (int k = 0; k < matrix.GetLength(1); k++) { // Loop over matrix[,k]
            Console.Write($" {matrix[j, k]}");
        }
        Console.WriteLine();
    }
}