首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 介面進階:多重實作與顯式實作機制詳解

     編輯:關於C語言

同一介面的多種實作策略

using System;

interface ICalculator {
    int Calculate(int x, int y);
}

class AddCalculator : ICalculator {
    public int Calculate(int x, int y) => x + y;
}

class SubCalculator : ICalculator {
    public int Calculate(int x, int y) => x - y;
}

class Program {
    static void Main() {
        ICalculator calc1 = new AddCalculator();
        ICalculator calc2 = new SubCalculator();
        Console.WriteLine(calc1.Calculate(3, 2)); // 5
        Console.WriteLine(calc2.Calculate(3, 2)); // 1
        Console.ReadKey();
    }
}

此為策略模式核心:介面定義契約,具體類別提供演算法變體,執行時動態切換。

顯式介面實作:解決同名衝突

using System;

interface ILogger { void Log(string msg); }
interface IAuditor { void Log(string msg); }

class Service : ILogger, IAuditor {
    // 顯式實作:不加 public,只能透過介面參考呼叫
    void ILogger.Log(string msg) => Console.WriteLine($"[LOG] {msg}");
    void IAuditor.Log(string msg) => Console.WriteLine($"[AUDIT] {msg}");

    // 隱式實作(公開方法)可共存
    public void Log(string msg) => Console.WriteLine($"[DEFAULT] {msg}");
}

class Program {
    static void Main() {
        Service svc = new Service();
        svc.Log("Hello");              // [DEFAULT] Hello

        ILogger logger = svc;
        logger.Log("Hello");           // [LOG] Hello

        IAuditor auditor = svc;
        auditor.Log("Hello");          // [AUDIT] Hello

        Console.ReadKey();
    }
}

顯式 vs 隱式實作比較

維度隱式實作顯式實作
語法public void Method()void IInterface.Method()
存取層級public無修飾詞(隱含 private)
呼叫方式類別實例、介面參考皆可僅透過介面參考
同名衝突無法區分完美解決
多型行為標準虛擬調度介面調度(非虛擬)

進階應用:介面隔離與依賴反轉

// 介面隔離:客戶端只依賴需要的介面
interface IReadOnlyRepository { T GetById(int id); IEnumerable GetAll(); }
interface IWriteRepository { void Add(T entity); void Update(T entity); void Delete(int id); }

// 具象類別實作多個介面
class UserRepository : IReadOnlyRepository, IWriteRepository {
    // 顯式實作區分讀寫介面
    User IReadOnlyRepository.GetById(int id) => /* 查詢 */;
    IEnumerable IReadOnlyRepository.GetAll() => /* 查詢 */;
    void IWriteRepository.Add(User entity) => /* 新增 */;
    // ...
}

// 高層模組依賴抽象
class UserService {
    private readonly IReadOnlyRepository _readRepo;
    private readonly IWriteRepository _writeRepo;
    public UserService(IReadOnlyRepository r, IWriteRepository w) {
        _readRepo = r; _writeRepo = w;
    }
}

最佳實踐清單

  • 預設使用隱式實作,API 更直觀
  • 同名衝突、需隱藏實作細節、實作多個同名介面方法 → 顯式實作
  • 介面盡量細小(ISP),避免「胖介面」
  • 公開 API 回傳介面型別而非具象類別(DIP)
  • C# 8.0+ 可在介面提供預設實作,減少破壞性變更
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved