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

Sự khác biệt giữa IEnumerator và IEnumerable Interface trong C #

IEnumerable và IEnumerator đều là giao diện trong C #.

IEnumerable là một giao diện xác định một phương thức GetEnumerator () duy nhất trả về giao diện IEnumerator.

Điều này hoạt động để truy cập chỉ đọc vào bộ sưu tập triển khai IEnumerable có thể được sử dụng với một câu lệnh foreach.

IEnumerator có hai phương thức MoveNext và Reset. Nó cũng có một thuộc tính gọi là Hiện tại.

Phần sau cho thấy việc triển khai IEnumerable và IEnumerator.

Ví dụ

class Demo : IEnumerable, IEnumerator {
   // IEnumerable method GetEnumerator()
   IEnumerator IEnumerable.GetEnumerator() {
      throw new NotImplementedException();
   }
   public object Current {
      get { throw new NotImplementedException(); }
   }
   // IEnumertor method
   public bool MoveNext() {
      throw new NotImplementedException();
   }
   // IEnumertor method
      public void Reset() {
      throw new NotImplementedException();
   }
}

Ở trên, bạn có thể thấy hai phương thức của IEnumerator.

// IEnumertor method
public bool MoveNext() {
   throw new NotImplementedException();
}

// IEnumertor method
public void Reset() {
   throw new NotImplementedException();
}