简体   繁体   English

如何为整个数组赋值0

[英]How to assign 0 to whole array

I have an array. 我有一个阵列。 int[] array = new int[10]; . I want to assign '0' to whole array without using loop means that 0 is to be stored in all of the indexes. 我想在不使用循环的情况下将'0'分配给整个数组意味着0将存储在所有索引中。 How would i do it. 我该怎么做

After creation all items of array will have default values, which is 0 for int. 创建之后,所有数组项都将具有默认值,对于int,该值为0。 So, you don't need to do anything here. 所以,你不需要在这里做任何事情。

From Arrays (C# Programming Guide) : 数组(C#编程指南)

The default values of numeric array elements are set to zero, and reference elements are set to null. 数值数组元素的默认值设置为零,引用元素设置为null。


Also from C# Specification 12.2 Array creation 也来自C#规范12.2数组创建

Elements of arrays created by array-creation-expressions are always initialized to their default value. 由array-creation-expression创建的数组元素始终初始化为其默认值。

5.2 Default values 5.2默认值

For a variable of a value-type, the default value is the same as the value computed by the value-type's default constructor 对于value-type的变量,默认值与value-type的默认构造函数计算的值相同

4.1.2 Default constructors 4.1.2默认构造函数

For sbyte, byte, short, ushort, int, uint, long, and ulong, the default value is 0. 对于sbyte,byte,short,ushort,int,uint,long和ulong,默认值为0。


but after assigning other values i want all the indexes to be 0 again so then how would i do it? 但在分配其他值后,我希望所有索引再次为0,那么我该怎么做呢?

UPDATE: You can use Array.Clear : 更新:您可以使用Array.Clear

Sets a range of elements in the Array to zero, to false, or to null, depending on the element type. 根据元素类型,将Array中的元素范围设置为零,为false或为null。

In your case: 在你的情况下:

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

Consider also to use List<int> instead of array - it allows to add/remove items dynamically. 还要考虑使用List<int>而不是array - 它允许动态添加/删除项目。

You don't need to do anything at all. 你根本不需要做任何事情。

Since int is a value type , all elements are initilialized to 0 as a default. 由于int值类型 ,因此默认情况下所有元素都初始化为0

From Arrays (C# Programming Guide) 来自Arrays (C# Programming Guide)

The default values of numeric array elements are set to zero, and reference elements are set to null. 数值数组元素的默认值设置为零,引用元素设置为null。


ok if i want it to be assigned to 3 then how would i do it? 好的,如果我想将它分配给3那么我该怎么做?

You can use for loop to assign them like; 你可以使用for循环来分配它们;

int[] array = new int[10];
for(int i = 0; i < array.Length; i++)
    array[i] = 3;

If you want to give back their default values (which is 0 in this case), you can create a new array or you can use Array.Clear method like; 如果要返回它们的默认值(在这种情况下为0 ),可以创建一个新数组,也可以使用Array.Clear方法;

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

If you really don't want to use any loop, you might need to use List<int> instead an array. 如果您确实不想使用任何循环,则可能需要使用List<int>而不是数组。 It has more functionality and it creates a clean list (without any default value). 它具有更多功能,并创建一个干净的列表(没有任何默认值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM