C#数组,如何创建空数组? [英] C# arrays, how to create empty array?
问题描述
我学习C#中,我的小学语文现在正在PHP之前。我想知道你如何(或者)C#创建一个空数组。
I'm learning c#, with my primary language before now being php. I was wondering how (or if) you could create an empty array in c#.
在PHP中,你可以创建一个数组,然后添加任意数量的条目吧。
In php, you can create an array, and then add any number of entries to it.
$multiples=array();
$multiples[] = 1;
$multiples[] = 2;
$multiples[] = 3;
在C#中,我无法做类似的事情:
In c#, I'm having trouble doing something similar:
int[] arraynums = new int[];
arraynums[] = 1;
arraynums[] = 2;
arraynums[] = 3;
这给错误数组创建必须有数组大小或数组初始化程序。如果我不知道我要多少个条目做,我该怎么办呢?有没有办法解决?
Which gives the error "array creation must have array size or array initializer." If I don't know how many entries I want to make, how do I do this? Is there a way around this?
推荐答案
如果你不事先知道的大小,使用列表<的而不是
; T&GT数组。一个数组,在C#中的大小是固定的,你在创建时必须指定大小。
If you don't know the size in advance, use a List<T>
instead of an array. An array, in C#, is a fixed size, and you must specify the size when creating it.
var arrayNums = new List<int>();
arrayNums.Add(1);
arrayNums.Add(2);
一旦你添加的项目,您可以通过索引提取它们,就像你会与一个数组:
Once you've added items, you can extract them by index, just like you would with an array:
int secondNumber = arrayNums[1];
这篇关于C#数组,如何创建空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!