在 C# 中,调整数组大小(在这种情况下增加其大小)会使用默认值初始化新段——这可靠吗?

In C# resizing an array (increasing its size in this case) initializes the new segment with default values – is this reliable?

在 C# 中调整数组大小(在这种情况下增加其大小)会使用默认值初始化新段 – 这可靠吗?

Array.Resize(ref bytes, bytes.Length + extra);

我确实看到了默认值(字节数组为 0),但是是否可以安全地将其作为所有基本类型的标准行为?在我的应用程序中,每一秒的节省都是一件大事,因此我认为如果默认情况下它已经可用,我可以避免不必要的循环来初始化新添加的段。 Microsoft .NET 文档没有明确说明这一事实:https://docs.microsoft.com/en-us/dotnet/api/system.array.resize?view=netframework-4.8 尽管示例有点暗示该行为。

是的,你可以放心。来自文档(强调我的):

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. array must be a one-dimensional array.

分配一个新数组保证用默认值填充它(实际上 "set all bits to 0"),所以如果我们相信描述,整个 Array.Resize 操作的结果确实会有默认值尚未从旧数组中复制的所有元素。

是的,它是可靠的。一种看待它的方式——如果新的数组元素不包含默认值,它们将包含什么?该方法不会弥补价值。

并不是说我通常会为框架代码编写单元测试,但这是测试预期行为的一种简单方法,尤其是在文档让我们不确定的情况下。

[TestMethod]
public void Resizing_array_appends_default_values()
{
    var dates = new DateTime[] {DateTime.Now};
    Array.Resize(ref dates, dates.Length + 1);
    Assert.AreEqual(dates.Last(), default(DateTime));

    var strings = new string[] { "x" };
    Array.Resize(ref strings, strings.Length + 1);
    Assert.IsNull(strings.Last());

    var objects = new object[] { 1, "x" };
    Array.Resize(ref objects, objects.Length + 1);
    Assert.IsNull(objects.Last());
}

不用说,我会在 运行 之后放弃这个单元测试。我不会犯的。