C# - 如何将数组声明为二维数组的列
问题描述:
我想创建一个二维数组,用其他数组来表示列。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}
};
但我得到一个控制台错误,告诉我,这不是拿起期望的长度。
我看了看周围的很多老问题,但他们从来没有真正弄清楚如何定义一个这样的数组。任何帮助,将不胜感激。
答
你可以声明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 ...
等。
答
这应该解决您的问题
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 },
};
答
它看起来像你想使用交错数组,只是需要改变itemList中初始化器到:
var itemList = new int[10][] { item0, item1, item2, item3, item4, item5, item6, item7, item8, item9 };
谢谢,交错数组似乎是这里的答案。然而,我得到另一个问题,我得到一个空引用控制台错误使用if(itemList [0] [0] == 1) - 我如何获取我的新锯齿阵列内的值? – Stephen
@Stephen'item [0]'是一个*数组*因此它的默认值是'null',直到您初始化为止;你正试图索引一个不存在的数组'null [0]'。这与你在执行'var myObjectArray = new object [5];'时得到的行为是一样的。 'myObjectArray [0]'是'null'。当数组被创建时,其成员被初始化为数组的类型默认值。 – InBetween
@stakz好了,我以为我有,但由于某种原因它仍然出现空。我基本上完成了item0 = new int [22] {0,0,0,0,0,0 ...};然后完成itemList = new int [10] [];接着是itemList [0] = item0; - 然后当我做如果(itemList [0] [0] == 0)我得到一个空引用,但我已经定义它已经0,或者我必须第二次定义它,一旦我已经初始化它进入第二个数组?它是否恢复为空? – Stephen