/ / Що не так з моїм вбудованим словом foreach / if? [дублікат] - c #, масиви

Що не так з моїм вбудованим твердженням foreach / if? [дублікат] - c #, масиви

int[][] multi = new int[2][];

multi[0] = new int[2];
multi[1] = new int[2];

multi[0][0] = 11;
multi[0][1] = 2;
multi[0][2] = 4;

multi[1][0] = 4;
multi[1][1] = 5;
multi[1][2] = 6;

Array.ForEach(
multi,
x => multi.Length != x.Length
? throw new Exception("The two dimensional arrays must be symmetrical."));

Я отримую виняток із переповненням і я не знаю, що я можу зробити тут, можна зробити?

Відповіді:

3 для відповіді № 1

The найближча причина від помилки

multi[0] = new int[2]; // multi[0] has 2 items: with indexes 0 and 1

...

multi[0][2] = 4;       // out of range: multi[0] doesn"t have 3d item (with index 2)

Можливо, ви захочете змінити ініціалізацію на

int[][] multi = new int[][] {
new int[] { 11, 2, 4},
new int[] {  4, 5, 6},
};

Ви працюєте з зубчастий, ні 2D масив; ось чому тест (ми хочемо multi бути площа масив) повинен бути

using System.Linq;

...

if (multi.Any(x => x == null || multi.Length != x.Length))
throw new Exception("The two dimensional arrays must be symmetrical.");

Зауваження: не кидай загальний Exception, але конкретний один, скажімо ArgumentException, ArgumentOutOfRangeException тощо.