如何在C#中初始化一个空数组?
问题描述:
是否可以在不指定大小的情况下创建空数组?
Is it possible to create an empty array without specifying the size?
例如,我创建了:
String[] a = new String[5];
我们可以创建没有大小的上述字符串数组吗?
Can we create the above string array without the size?
答
如果您要使用事先不知道其大小的集合,那么有比数组更好的选择.
If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.
改为使用List<string>
-它允许您添加所需数量的项,如果需要返回数组,请在变量上调用ToArray()
.
Use a List<string>
instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray()
on the variable.
var listOfStrings = new List<string>();
// do stuff...
string[] arrayOfStrings = listOfStrings.ToArray();
如果您必须创建一个空数组,则可以执行以下操作:
If you must create an empty array you can do this:
string[] emptyStringArray = new string[0];