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

标签 c# arrays

我有一个数组。 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/

相关文章:

c# - 单独服务中的 Blazor Controller

c# - 获取从 C# 代码到 javascript 的响应

c# - Xamarin 4 中旧的 ListView 和新的 CollectionView 有什么区别?

javascript - 检查文本中的任何单词是否与数组匹配

c - 如何写入结构体数组的第二个元素?在C中

c# - 如何检查登录操作中是否存在用户?

c# - 调用 ExecuteReader 时从 DAL 基类处置 SqlConnection

javascript - 我应该每次都创建一个 ArrayBuffer 还是应该清除以前创建的一个?

javascript - 返回数字的总和(正数或负数)

c - 没有新数组的字符串反转