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

Phương thức Array.GetEnumerator trong C #

Phương thức Array.GetEnumerator () trong C # được sử dụng để trả về IEnumerator cho Array.

Cú pháp

Sau đây là cú pháp -

public virtual System.Collections.IEnumerator GetEnumerator ();

Ví dụ

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

using System;
using System.Collections;
public class Demo{
   public static void Main(){
      int j = 0;
      Console.WriteLine("Array elements...");
      string[] arr = { "car", "bike", "truck", "bus"};
      for (int i = 0; i < arr.Length; i++){
         Console.Write("{0} ", arr[i]);
      }
      Console.WriteLine();
      IEnumerator newEnum = arr.GetEnumerator();
      Console.WriteLine("IEnumerator for the Array...");
      while ((newEnum.MoveNext()) && (newEnum.Current != null)) {
         Console.WriteLine("[{0}] {1}", j++, newEnum.Current);
      }
   }
}

Đầu ra

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

Array elements...
car bike truck bus
IEnumerator for the Array...
[0] car
[1] bike
[2] truck
[3] bus