IEnumerable และ IEnumerator เป็นอินเทอร์เฟซใน C #
IEnumerable เป็นอินเทอร์เฟซที่กำหนดวิธีการเดียว GetEnumerator() ที่ส่งคืนอินเทอร์เฟซ IEnumerator
ใช้งานได้สำหรับการเข้าถึงแบบอ่านอย่างเดียวในคอลเล็กชันที่นำ IEnumerable ไปใช้กับคำสั่ง foreach
IEnumerator มีสองวิธีคือ MoveNext และ Reset นอกจากนี้ยังมีคุณสมบัติที่เรียกว่าปัจจุบัน
ต่อไปนี้แสดงการใช้งาน IEnumerable และ IEnumerator
ตัวอย่าง
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();
}
} ด้านบน คุณจะเห็น IEnumerator สองวิธี
// IEnumertor method
public bool MoveNext() {
throw new NotImplementedException();
}
// IEnumertor method
public void Reset() {
throw new NotImplementedException();
}