gpt4 book ai didi

c# - 是否可以在不初始化内部对象的情况下将数组初始化为容量?

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:04 25 4
gpt4 key购买 nike

假设我知道我需要的数组的长度和类型,我可以这样做:

KnownType arrayName = new KnownType[knownSize];

但此代码还将初始化内部对象,请考虑我只是从另一个数组复制到这个新数组的情况。我不需要初始化这些内部对象。我只需要可以存储所述对象的空白空间。

有没有办法在不初始化内部对象的情况下创建特定容量的数组?

最佳答案

Is there a way to create an array of a specific capacity without initializing the internal objects?

简而言之:不。您至少始终坚持使用默认值。

至于documentation在创建 new 数组时告诉我们:

The new operator is used to create the array and initialize the array elements to their default values.

在这种情况下,引用类型将得到 null

初始化默认值听起来很合理,因为内存已经分配并且不能用于其他任何事情。那么为什么不初始化这些值。

这是文档中的示例:

int[] array = new int[5];

This array contains the elements from array[0] to array[4]. [...] In this example, all the array elements are initialized to zero.

编辑:区分引用值类型

Consider the following array declaration:

SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type, the statement creates an array of 10 elements, each of which has the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.

关于c# - 是否可以在不初始化内部对象的情况下将数组初始化为容量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52145228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com