2016-09-22 84 views
0

我想創建一個二維數組,用其他數組來表示列。C# - 如何將數組聲明爲二維數組的列

繼承人是我想要做的事:

public int[] item0; 
    public int[] item1; 
    public int[] item2; 
    public int[] item3; 
    public int[] item4; 
    public int[] item5; 
    public int[] item6; 
    public int[] item7; 
    public int[] item8; 
    public int[] item9; 

     item0 = new int[22]; 
     item1 = new int[22]; 
     item2 = new int[22]; 
     item3 = new int[22]; 
     item4 = new int[22]; 
     item5 = new int[22]; 
     item6 = new int[22]; 
     item7 = new int[22]; 
     item8 = new int[22]; 
     item9 = new int[22]; 
     itemList = new int[10,22] { 
{item0}, 
{item1}, 
{item2}, 
{item3}, 
{item4}, 
{item5}, 
{item6}, 
{item7}, 
{item8}, 
{item9} 
}; 

但我得到一個控制檯錯誤,告訴我,這不是拿起期望的長度。

我看了看周圍的很多老問題,但他們從來沒有真正弄清楚如何定義一個這樣的數組。任何幫助,將不勝感激。

回答

1

你可以聲明itemList爲 「鋸齒狀」 陣列:

var itemList = new int[][] { 
    item0, 
    item1, 
    new int[] { 1, 2, 3 }, 
    new int[] { 1, 2, 3, 4, 5, … }, 
    item4, 
    item5, 
    … 
}; 

我已經包含了對既有int[]陣列的參考(item0item1等)以及上述示例中的內聯陣列實例(new int[] { … })。此外,請注意,對於鋸齒形陣列,itemList中的單個數組項不需要具有相同的長度。這表明鋸齒陣列實際上不是二維的;它是一個數組數組。

+0

謝謝,交錯數組似乎是這裏的答案。然而,我得到另一個問題,我得到一個空引用控制檯錯誤使用if(itemList [0] [0] == 1) - 我如何獲取我的新鋸齒陣列內的值? – Stephen

+1

@Stephen'item [0]'是一個*數組*因此它的默認值是'null',直到您初始化爲止;你正試圖索引一個不存在的數組'null [0]'。這與你在執行'var myObjectArray = new object [5];'時得到的行爲是一樣的。 'myObjectArray [0]'是'null'。當數組被創建時,其成員被初始化爲數組的類型默認值。 – InBetween

+0

@stakz好了,我以爲我有,但由於某種原因它仍然出現空。我基本上完成了item0 = new int [22] {0,0,0,0,0,0 ...};然後完成itemList = new int [10] [];接着是itemList [0] = item0; - 然後當我做如果(itemList [0] [0] == 0)我得到一個空引用,但我已經定義它已經0,或者我必須第二次定義它,一旦我已經初始化它進入第二個數組?它是否恢復爲空? – Stephen

1

你不需要在開始時做所有的事情。多維數組不能鋸齒狀,並自動使所有內部數組的大小22,如果你只是做

itemList = new int[10,22]; 

此外,你可以像這樣初始化的:

itemList = new int[10,22] { 
    {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 16, 17, 18, 19, 20, 21, 22}, 
    {1, 3, 5, 7, 9 ... 

等。

0

這應該解決您的問題

 var itemList = new int[][] { 
     item0, 
     item1, 
     item2, 
     item3, 
     item4, 
     item5, 
     item6, 
     }; 

不過我建議你做這樣

 int[,] itemList = new int[,] 
     { 
      {1,2,3,4,5 }, 
      {1,2,3,4,5 }, 
      {1,2,3,4,5 }, 
     }; 
1

它看起來像你想使用交錯數組,只是需要改變itemList中初始化器到:

var itemList = new int[10][] { item0, item1, item2, item3, item4, item5, item6, item7, item8, item9 };