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

例如,我创建了:

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;
}

其他回答

试试这个:

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

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

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

在你的情况下:

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

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

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

然后是l.ToArray()。

这里有一个真实的例子。在这种情况下,必须首先将数组foundFiles初始化为零长度。

(正如在其他回答中强调的那样:这不会初始化一个元素,尤其是索引为0的元素,因为这意味着数组的长度为1。数组在这行之后的长度为零!)

如果省略了part = string[0],则有编译器错误!

这是因为没有重新抛出的捕捉块。c#编译器识别代码路径,函数Directory.GetFiles()可以抛出异常,这样数组就可以未初始化。

在有人说,不重新抛出异常将是糟糕的错误处理之前:这不是真的。错误处理必须符合要求。

在这种情况下,假定在无法读取目录的情况下,程序应该继续,而不是中断——最好的例子是一个遍历目录结构的函数。这里的错误处理只是记录它。当然,这可以做得更好,例如收集所有失败的GetFiles(Dir)调用的目录在一个列表中,但这将在这里走得太远。

只要说明避免throw是一个有效的场景就足够了,因此数组必须初始化为长度为0。在catch块中这样做就足够了,但这将是糟糕的风格。

调用GetFiles(Dir)来调整数组的大小。

string[] foundFiles= new string[0];
string dir = @"c:\";
try
{
    foundFiles = Directory.GetFiles(dir);  // Remark; Array is resized from length zero
}
// Please add appropriate Exception handling yourself
catch (IOException)
{
  Console.WriteLine("Log: Warning! IOException while reading directory: " + dir);
  // throw; // This would throw Exception to caller and avoid compiler error
}

foreach (string filename in foundFiles)
    Console.WriteLine("Filename: " + filename);

简单优雅!

string[] array = {}