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

例如,我创建了:

String[] a = new String[5];

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


当前回答

你可以:

string[] a = { String.Empty };

注意:OP意味着不需要指定大小,而不是使数组无大小

其他回答

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

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

然后是l.ToArray()。

性能规则CA1825:避免分配零长度的数组。

规则解释: 初始化零长度数组会导致不必要的内存分配。相反,通过调用array来使用静态分配的空数组实例。空方法。

在你的情况下:

var a = Array.Empty<string>(); 

如果要使用一个事先不知道其大小的集合,有比数组更好的选择。

使用List<string>代替-它将允许您根据需要添加任意数量的项,如果您需要返回一个数组,请在变量上调用ToArray()。

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();

如果你必须创建一个空数组,你可以这样做:

string[] emptyStringArray = new string[0]; 

结合@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

你可以使用数组。空方法(至少在。net Core中)

string ToCsv(int[] myArr = null) { // null by default

    // affect an empty array if the myArr is null
    myArr ??= Array.Empty<int>();
    
    //... do stuff
    string csv = string.Join(",", myArr);

    return csv;
}