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