gpt4 book ai didi

c# - 如何将 0 分配给整个数组

转载 作者:IT王子 更新时间:2023-10-29 04:33:54 26 4
gpt4 key购买 nike

我有一个数组。 int[] array = new int[10];。我想在不使用循环的情况下将“0”分配给整个数组,这意味着 0 将存储在所有索引中。我该怎么做。

最佳答案

创建后数组的所有项都将具有默认值,对于 int 为 0。因此,您无需在此处执行任何操作。

来自 Arrays (C# Programming Guide) :

The default values of numeric array elements are set to zero, and reference elements are set to null.


同样来自 C# 规范 12.2 Array creation

Elements of arrays created by array-creation-expressions are always initialized to their default value.

5.2 Default values

For a variable of a value-type, the default value is the same as the value computed by the value-type's default constructor

4.1.2 Default constructors

For sbyte, byte, short, ushort, int, uint, long, and ulong, the default value is 0.


but after assigning other values i want all the indexes to be 0 again so then how would i do it?

更新:您可以使用 Array.Clear :

Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.

在你的情况下:

Array.Clear(array, 0, array.Length);

也可以考虑使用 List<int>而不是数组 - 它允许动态添加/删除项目。

关于c# - 如何将 0 分配给整个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22218066/

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