c# -如何将数组声明为2D数组的列

本文关键字:数组 2D 声明 | 更新日期: 2023-09-27 18:08:09

我正在尝试创建一个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} 
};

但是我得到一个控制台错误,告诉我它没有选择预期的长度。

我看了很多老问题,但他们从来没有真正澄清如何定义这样一个数组。

c# -如何将数组声明为2D数组的列

您可以将itemList声明为"锯齿"数组:

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

在上面的例子中,我包括了对已有的int[]数组(item0, item1等)以及内联数组实例化(new int[] { … })的引用。此外,请注意,对于锯齿数组,itemList中的单个数组项不需要具有相同的长度。这表明锯齿数组实际上不是二维的;

你不需要一开始就做这些。多维数组不能锯齿化,如果您只执行

,就会自动使所有内部数组的大小为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[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 },
        };