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

การทำงานของ Interface ใน C#


Interface กำหนด Contract (สัญญา) ที่ Class หรือ Struct ต้อง Implement สามารถประกอบด้วย Methods, Properties, Events, Indexers Interface คล้าย Class แต่ไม่มี Data เก็บไว้ เพียงระบุพฤติกรรมที่ Class ที่ Implement ต้องทำ

Class สามารถ Implement Interface ได้หลาย Interface ในการ Implement ต้องมี Public Member ที่ตรงกับ Signature ของ Interface Member (ชื่อและพารามิเตอร์เหมือนกัน)

ตัวอย่าง IComparer ใน System.Collections กำหนด Contract สำหรับเปรียบเทียบสองออบเจกต์ คลาส Car Implement IDriver:

public interface IDriver
{
    void Drive();
}

public class Car : IDriver
{
    public string Name { get; set; }
    public int Speed { get; set; }
    public void Drive()
    {
        Console.WriteLine($"{Name}: {Speed}");
    }
}

Member ทุกตัวใน Interface เป็น Implicitly Abstract (ไม่มี Implementation) และเป็น Public เสมอ ไม่สามารถใช้ Access Modifier กับ Member ได้ Class ที่ Implement ต้องมี Public Method ตรงกับ Interface

Interface สามารถ Extend Interface อื่นได้:

public interface IPerformer { void Perform(); }
public interface ISinger : IPerformer { void Sing(); }

Interface ช่วยให้รวมพฤติกรรมจากหลายแหล่งใน Class เดียว (Multiple Implementation) เนื่องจาก C# ไม่รองรับ Multiple Inheritance แบบ C++

ข้อจำกัด: Interface ยืดหยุ่นน้อยกว่า Class ตอน Expose API หากเปลี่ยน Contract ของ Interface ทุก Class ที่ Implement จะ Break และต้องอัปเดต

ตัวอย่างโค้ด

using System;

class Program
{
    static void Main()
    {
        var car1 = new Car { Name = "Honda", Speed = 100 };
        var car2 = new Car { Name = "Toyota", Speed = 70 };
        car1.Drive();
        car2.Drive();
    }
}

public interface IDriver { void Drive(); }

public class Car : IDriver
{
    public string Name { get; set; }
    public int Speed { get; set; }
    public void Drive() => Console.WriteLine($"{Name}: {Speed}");
}

ผลลัพธ์

Honda: 100
Toyota: 70