IEnumerable và IEnumerator đều là interface trong C#.
IEnumerable là interface định nghĩa một phương thức duy nhất GetEnumerator() trả về interface IEnumerator.
Điều này hoạt động cho quyền truy cập chỉ đọc vào tập hợp triển khai IEnumerable có thể được sử dụng với 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à Current.
Đoạn sau minh họa việc triển khai IEnumerable và IEnumerator.
Ví dụ
class Demo : IEnumerable, IEnumerator {
// Phương thức IEnumerable GetEnumerator()
IEnumerator IEnumerable.GetEnumerator() {
throw new NotImplementedException();
}
public object Current {
get { throw new NotImplementedException(); }
}
// Phương thức IEnumerator
public bool MoveNext() {
throw new NotImplementedException();
}
// Phương thức IEnumerator
public void Reset() {
throw new NotImplementedException();
}
}
Trên đây bạn có thể thấy hai phương thức của IEnumerator.
// Phương thức IEnumerator
public bool MoveNext() {
throw new NotImplementedException();
}
// Phương thức IEnumerator
public void Reset() {
throw new NotImplementedException();
}