2017-12-28 13 views
-13
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.")); 

私はオーバーフロー例外を取得し、ここで何をしようとしているのかわからないのですか?エラーのインラインforeach/if文で何が問題になっていますか?

+10

これはコンパイルされますか? – Evk

+6

'multi [0] = new int [2];'は長さ= 2の配列を作成します。次に 'multi [0] [2] = 4;'は配列の3番目の要素を設定しようとします。 –

+1

このような重複の場合、Typo System.IndexOutOfRangeExceptionを編集できますか? –

答えて

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) 

であるあなたは、あなたがいない2D配列、ギザギザで作業している

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

に初期化を変更することもできます。一般Exceptionが、特定 1、ArgumentExceptionを言う、ArgumentOutOfRangeExceptionなど

をスローしません:テストは(我々は multi平方配列になりたい)

using System.Linq; 

... 

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

備考あるべき理由です

+2

そして、彼はラムダのような三項演算子を使用することはできません:) – EpicKip

関連する問題