如何在 C# 中初始化一个空数组?

如何在 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 - 它将允许您根据需要添加任意数量的项目,如果您需要返回数组,请调用 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];