C#中的Array.Clear()方法用于清除数组中的元素并将它们设置为其默认值。元素在一定范围内清除。语法如下-
public static void Clear (Array arr, int index, int len);
在这里,arr是要清除其元素的数组,索引是要清除的元素的开始索引,而len是要清除的元素的计数。
现在让我们看一个实现Array.Clear()方法的示例-
using System;
public class Demo{
public static void Main(){
Console.WriteLine("Array elements...");
int[] arr = { 20, 50, 100, 150, 200, 300, 400, 450, 500, 600, 800, 1000, 1500, 2000 };
for (int i = 0; i < 14; i++){
Console.Write("{0} ", arr[i]);
}
Console.WriteLine();
Console.WriteLine("Clearing some elements in a range...");
Array.Clear(arr, 5, 9);
for (int i = 0; i < 14; i++){
Console.Write("{0} ", arr[i]);
}
Console.WriteLine();
}
}输出结果
这将产生以下输出-
Array elements... 20 50 100 150 200 300 400 450 500 600 800 1000 1500 2000 Clearing some elements in a range... 20 50 100 150 200 0 0 0 0 0 0 0 0 0
让我们看另一个例子-
using System;
public class Demo{
public static void Main(){
Console.WriteLine("Array elements...");
int[,] arr = { {20, 50, 100, 120}, {150, 200, 300, 350}, {400, 450, 500, 550}, {600, 800, 1000, 1200} };
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
Console.Write("{0} ", arr[i,j]);
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Clearing some elements in a range...");
Array.Clear(arr, 5, 9);
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
Console.Write("{0} ", arr[i,j]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}输出结果
这将产生以下输出-
Array elements... 20 50 100 120 150 200 300 350 400 450 500 550 600 800 1000 1200 Clearing some elements in a range... 20 50 100 120 150 0 0 0 0 0 0 0 0 0 1000 1200