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

例如,我创建了:

String[] a = new String[5];

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


当前回答

你可以使用数组。空方法(至少在。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;
}

其他回答

可以在运行时定义数组大小。

这将允许您动态地计算数组的大小。但是,一旦定义,大小是不可变的。

Array a = Array.CreateInstance(typeof(string), 5);

你可以使用数组。空方法(至少在。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;
}

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

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

然后是l.ToArray()。

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

string[] a = new string[0];

在. net 4.6中,首选的方法是使用一个新的方法Array。空:

String[] a = Array.Empty<string>();

实现很简洁,使用了泛型类中的静态成员在。net中的行为:

public static T[] Empty<T>()
{
    return EmptyArray<T>.Value;
}

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

(为了清晰起见,删除了与合同相关的代码)

参见:

数组中。参考源上的空源代码 Array.Empty<T>()简介 Marc Gravell - Allocaction,分配,分配-我最喜欢的关于微小隐藏分配的帖子。