Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ประเภทอินเทอร์เฟซ (Interface Types) ใน C#

อินเทอร์เฟซ (Interface) ใน C# กำหนดสัญญาสำหรับคลาสที่จะต้องปฏิบัติ โดยประกอบด้วยการประกาศสมาชิกเท่านั้น ได้แก่ คุณสมบัติ (Properties), เมธอด (Methods), และเหตุการณ์ (Events) โดยไม่มีการนำไปใช้งาน (Implementation)

อินเทอร์เฟซสำคัญใน .NET

  • IEnumerable - อินเทอร์เฟซฐานสำหรับคอลเลกชัน Generic ทั้งหมด ใช้สำหรับการวนลูปด้วย foreach
  • IList - อินเทอร์เฟซ Generic สำหรับรายการที่เข้าถึงด้วยดัชนีได้ รองรับโดยอาร์เรย์และ List
  • IDictionary - อินเทอร์เฟซสำหรับคอลเลกชันแบบคีย์-ค่า (Dictionary)

โครงสร้าง IEnumerable และ IEnumerator

IEnumerable กำหนดเมธอดเดียวคือ GetEnumerator() ที่ส่งคืน IEnumerator ส่วน IEnumerator มี:

  • MoveNext() - เลื่อนไปยังองค์ประกอบถัดไป
  • Reset() - รีเซ็ตตำแหน่งกลับไปจุดเริ่มต้น
  • Current - คุณสมบัติสำหรับดึงค่าปัจจุบัน

ตัวอย่างการ Implement IEnumerable

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

หมายเหตุ: ในการใช้งานจริง ควรใช้ IEnumerable<T> และ IEnumerator<T> แบบ Generic เพื่อความปลอดภัยของประเภท (Type Safety) และประสิทธิภาพที่ดีกว่า