簡體   English   中英

C#-如何將數組聲明為2D數組的列

[英]C# - how to declare arrays as columns of a 2D array

我正在嘗試創建2D數組,並使用其他數組來表示列。

這是我想做的事情:

   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} 
};

但是我收到一個控制台錯誤,告訴我這沒有達到預期的長度。

我環顧了許多舊問題,但它們從未真正闡明如何定義這樣的數組。 任何幫助,將不勝感激。

您不需要一開始就做所有的事情。 多維數組不能鋸齒,只要簡單地做即可自動使所有內部數組的大小為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 ...

等等。

您可以將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的單個數組項不必具有相同的長度。 這表明鋸齒狀數組實際上不是二維的; 它是一個數組數組。

看起來您想使用鋸齒狀的數組,只需要將itemList初始化程序更改為:

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

這應該可以解決您的問題

        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 },
        };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM