如何在C#中初始化一个空数组? [英] How do I initialize an empty array in 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<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];
这篇关于如何在C#中初始化一个空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文