如何初始化在C#空数组 [英] How to initialize 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.
使用列表<串>
而不是 - 它可以让你根据需要添加尽可能多的项目,如果你需要返回一个数组,调用 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屋!
查看全文