2016-08-19 131 views
-4

我有這個類在C#中陣列陣列的數組C#

public static class Fases 
{ 
    public static int [,,] fase1 = new int[, , ] { 
     {{1},{1 ,3}}, 
     {{2},{2, 2, 2}, {2, 2, 2 }}, 
     {{2}, {3, 1, 1, 1}, {3, 1, 1, 1}} 
    }; 
} 

當我做

Fases.fase1[0, 1, 1] 

它拋出IndexOutOfRangeException

謝謝!

+6

你不應該訪問像'Fases.fase1數組[0] [1] [1] '? – Andrew

+3

此代碼不能編譯。 –

+0

這不會編譯。請參閱[多維數組初始化](https://msdn.microsoft.com/en-IN/library/2yd9wwz4.aspx) –

回答

1

你有什麼不是一個數組數組,它​​是一個3維數組。多維數組必須具有統一的佈局,由於內部數組的長度不同,您的代碼將無法編譯。

爲了得到陣列的數組的數組代碼將需要

using System; 

public class Program 
{ 
    public static void Main() 
    { 
     var result = Fases.fase1[0][1][1]; 
     Console.WriteLine(result); 
    } 
} 

public static class Fases 
{ 
    public static int [][][] fase1 = new int[][][] { 
     new int [][] {new int[] {1}, new int[] {1 ,3}}, 
     new int [][] {new int[] {2}, new int[] {2, 2, 2}, new int[] {2, 2, 2 }}, 
     new int [][] {new int[] {2}, new int[] {3, 1, 1, 1}, new int[] {3, 1, 1, 1}} 
    }; 
} 

which compiles and runs

+0

請注意,內部數組類型可由編譯器推斷。例如:'new int [] [] {new [] {1},new [] {1,3}}}' –