Computer >> Máy Tính >  >> Lập trình >> C#

Phương thức Array.Clear () trong C #

Phương thức Array.Clear () trong C # được sử dụng để xóa các phần tử trong một mảng và đặt chúng thành mặc định của nó. Các phần tử được xóa trong một phạm vi. Cú pháp như sau -

Cú pháp

public static void Clear (Array arr, int index, int len);

Ở đây, arr là mảng có các phần tử cần xóa, index là chỉ số đầu của các phần tử cần xóa và len là số lượng các phần tử cần xóa.

Bây giờ chúng ta hãy xem một ví dụ để triển khai phương thức Array.Clear () -

Ví dụ

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();
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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

Hãy để chúng tôi xem một ví dụ khác -

Ví dụ

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();
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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