我的内联foreach / if语句出了什么问题?

时间:2017-12-28 14:49:54

标签: c# arrays

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."));

我收到溢出异常,我不确定我在这里尝试做什么可以做到?

1 个答案:

答案 0 :(得分:3)

错误的直接原因

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 square 数组)应该是

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,{{1等等。