【发布时间】:2011-02-10 00:55:19
【问题描述】:
我有一个全局变量int[],我想清除它的数据并在循环中再次填充。
这在 C# 中怎么可能?
【问题讨论】:
-
C# 中如何拥有全局变量?
-
@rep_movsd 这是另一个问题;)哈哈
-
循环的每次迭代中元素的数量是否会发生变化?看看代码就好了。
我有一个全局变量int[],我想清除它的数据并在循环中再次填充。
这在 C# 中怎么可能?
【问题讨论】:
静态Array.Clear() 方法“将数组中的一系列元素设置为零、假或无,具体取决于元素类型”。如果要清除整个数组,可以使用此方法并将其提供0 作为起始索引并提供myArray.Length 作为长度:
Array.Clear(myArray, 0, myArray.Length);
【讨论】:
.Length 属性是只读信息,不是变量。 c# 数组构造完成后,不能改变其长度。
==。可以合理地(没有问题细节的上下文)将“清除数组”解释为“空数组”,并初始化为长度 0。不知道为什么;只是为了提供 1_bug 评论的替代方案。
这不是您帖子的正确答案,但您可以根据需要使用此逻辑。 这是取自here的代码片段
using System;
class ArrayClear
{
public static void Main()
{
int[] integers = { 1, 2, 3, 4, 5 };
DumpArray ("Before: ", integers);
Array.Clear (integers, 1, 3);
DumpArray ("After: ", integers);
}
public static void DumpArray (string title, int[] a)
{
Console.Write (title);
for (int i = 0; i < a.Length; i++ )
{
Console.Write("[{0}]: {1, -5}", i, a[i]);
}
Console.WriteLine();
}
}
这个输出是:
Before: [0]: 1 [1]: 2 [2]: 3 [3]: 4 [4]: 5
After: [0]: 1 [1]: 0 [2]: 0 [3]: 0 [4]: 5
【讨论】:
为什么不直接创建新数组并将其分配给现有的数组变量?
x = new int[x.length];
【讨论】:
用列表代替会不会更容易。
public List<int> something = new List<int>();
然后:
something.Add(somevalue);
并清除:
something.Clear();
【讨论】:
int[] x
int[] array_of_new_values
for(int i = 0 ; i < x.Length && i < array_of_new_values.Length ;i++)
{
x[i] = array_of_new_values[i]; // this will give x[i] its new value
}
为什么要清除它?只需分配新值。
【讨论】:
对于二维数组,你应该这样做:
Array.Clear(myArray, 0, myArray.GetLength(0)*myArray.GetLength(1));
【讨论】:
myArray.Length 是 2D 数组myArray.GetLength(0)*myArray.GetLength(1) 的缩写。