是否可以创建一个空数组而不指定大小?

例如,我创建了:

String[] a = new String[5];

我们可以创建上面的字符串数组没有大小?


当前回答

你可以初始化它的大小为0,但你必须重新初始化它,当你知道大小是什么,因为你不能追加到数组。

string[] a = new string[0];

其他回答

我试过了:

string[] sample = new string[0];

但我只能插入一个字符串,然后我得到一个exceptionOutOfBound错误,所以我只是简单地为它输入一个大小,比如

string[] sample = new string[100];

或者另一种适合我的方法:

List<string> sample = new List<string>();

为列表赋值:

sample.Add(your input);

结合@nawfal和@Kobi的建议:

namespace Extensions
{
    /// <summary> Useful in number of places that return an empty byte array to avoid unnecessary memory allocation. </summary>
    public static class Array<T>
    {
        public static readonly T[] Empty = new T[0];
    }
}

使用的例子:

Array<string>.Empty

更新2019-05-14

(致@Jaider你)

最好使用。net API:

public static T[] Empty<T> ();

https://learn.microsoft.com/en-us/dotnet/api/system.array.empty?view=netframework-4.8

适用于:

.NET Core: 3.0预览5 2.2 2.1 2.0 1.1 1.0

.NET Framework: 4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 .NET Framework

.NET标准:2.1预览2.0 1.6 1.5 1.4 1.3

...

HTH

试试这个:

string[] a = new string[] { };

我知道数组不能没有大小,但你可以用

List<string> l = new List<string>() 

然后是l.ToArray()。

简单优雅!

string[] array = {}