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 เปรียบเทียบ
| คุณสมบัติ | Implicit | Explicit |
|---|---|---|
| Syntax | public void Method() | void IInterface.Method() |
| Access Modifier | Public | ไม่มี (Private to Interface) |
| เข้าถึงจาก Class | ได้ | ไม่ได้ |
| เข้าถึงจาก Interface | ได้ | ได้ |
| ชื่อซ้ำได้ไหม | ไม่ได้ | ได้ |
เมื่อไหร่ควรใช้ Explicit?
- ชื่อ Member ซ้ำกัน ระหว่าง Multiple Interfaces (เหตุหลัก)
- ซ่อน Implementation Detail ไม่ให้ Client เรียกโดยตรงจาก Concrete Type
- Versioning: เพิ่ม Member ใหม่ใน Interface โดยไม่ Break Existing Code
- 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 เพื่ออะไร