Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách hoạt động của Interface trong C#

Interface định nghĩa contract (hợp đồng) mà class hoặc struct sẽ implement. Chứa method, property, event, indexer. Interface giống class nhưng không giữ dữ liệu, chỉ chỉ định hành vi.

Class có thể implement nhiều interface. Để implement member của interface, class phải có public member cùng tên và chữ ký (signature).

Ví dụ IComparer trong System.Collections định nghĩa contract so sánh 2 đối tượng. Class 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}");
    }
}

Tất cả member trên interface ngầm abstract (không implementation). Mọi member đều public, không dùng access modifier. Class implement phải cung cấp public method.

Interface có thể kế thừa interface khác:


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

Interface cho phép gom hành vi từ nhiều nguồn vào một class (C# không hỗ trợ đa kế thừa class như C++).

Nhược điểm: Interface kém linh hoạt hơn class khi expose API. Thay đổi contract interface → tất cả class implement bị break và phải cập nhật.

Ví dụ

using System;

class Program
{
    static void Main()
    {
        var carOne = new Car { Name = "Honda", Speed = 100 };
        var carTwo = new Car { Name = "Toyota", Speed = 70 };
        carOne.Drive();
        carTwo.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}");
    }
}

Kết quả đầu ra

Honda: 100
Toyota: 70