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

Explicit Interface Implementation ใน C# คืออะไร และเมื่อไหร่ใช้

Explicit Interface Implementation คืออะไร?

เมื่อ Class Implement Interface 2 ตัวที่มี Member ชื่อและ Signature เหมือนกัน ใช้ Explicit Implementation เพื่อแยก Implementation แยกตาม Interface

  • Syntax: InterfaceName.MemberName
  • Member นี้ ไม่เป็น Public ของ Class
  • เข้าถึงได้ เฉพาะผ่าน Interface Reference เท่านั้น
  • ไม่ต้องมี Access Modifier (Implicitly Private)

ตัวอย่าง: Method ชื่อซ้ำใน 2 Interfaces


interface ICar
{
    void Display();
}

interface IBike
{
    void Display();
}

class ShowRoom : ICar, IBike
{
    // Explicit Implementation - แยกตาม Interface
    void ICar.Display()
    {
        Console.WriteLine("Displaying Car Info");
    }
    
    void IBike.Display()
    {
        Console.WriteLine("Displaying Bike Info");
    }
}

class Program
{
    static void Main()
    {
        ShowRoom showroom = new ShowRoom();
        
        // ❌ ไม่สามารถเรียกได้ - ไม่ใช่ Public Member ของ ShowRoom
        // showroom.Display(); // Compile Error
        
        // ✅ ต้อง Cast เป็น Interface ก่อน
        ICar car = showroom;
        car.Display(); // Output: Displaying Car Info
        
        IBike bike = showroom;
        bike.Display(); // Output: Displaying Bike Info
        
        Console.ReadKey();
    }
}

Implicit vs Explicit เปรียบเทียบ

คุณสมบัติImplicitExplicit
Syntaxpublic void Method()void IInterface.Method()
Access ModifierPublicไม่มี (Private to Interface)
เข้าถึงจาก Classได้ไม่ได้
เข้าถึงจาก Interfaceได้ได้
ชื่อซ้ำได้ไหมไม่ได้ได้

เมื่อไหร่ควรใช้ Explicit?

  1. ชื่อ Member ซ้ำกัน ระหว่าง Multiple Interfaces (เหตุหลัก)
  2. ซ่อน Implementation Detail ไม่ให้ Client เรียกโดยตรงจาก Concrete Type
  3. Versioning: เพิ่ม Member ใหม่ใน Interface โดยไม่ Break Existing Code
  4. Legacy/COM Interop: Match Signature ที่กำหนด

Property และ Event ก็ทำได้


interface IReadable
{
    string Content { get; }
}

interface IWritable
{
    string Content { set; }
}

class Document : IReadable, IWritable
{
    private string _content;
    
    string IReadable.Content 
    { 
        get => _content; 
    }
    
    string IWritable.Content 
    { 
        set => _content = value; 
    }
}

Best Practice

  • ใช้ Implicit เป็นหลัก (ง่าย อ่านง่าย)
  • ใช้ Explicit กรณีบังคับ (ชื่อซ้ำ, ต้องการซ่อน)
  • Document ให้ชัดเจน ว่า Member นี้ Explicit เพื่ออะไร