介面命名慣例以 I 開頭。定義「能做什麼」,不關心「怎麼做」。本文以用戶操作介面為例,展示 MySQL 升級 SQL Server 時的無縫切換,並說明介面繼承規則。
using System;
namespace gosoa.com.cn
{
public interface IUserOperation
{
bool UserExists(string username);
bool UpdateUserPwd(string newPwd, string oldPwd);
}
public class SqlUserOperation : IUserOperation
{
string uname = "pan";
public string oldPwd = "gosoa.com.cn";
public bool UserExists(string username)
{
return username == uname;
}
public bool UpdateUserPwd(string newPwd, string oldPwd)
{
return newPwd == oldPwd; // 簡化邏輯
}
}
public class MainClass
{
static void Main(string[] args)
{
string newPwd = Console.ReadLine();
string username = Console.ReadLine();
SqlUserOperation one = new SqlUserOperation();
IUserOperation two = new SqlUserOperation(); // 介面型別參考
if (two.UserExists(username)) Console.WriteLine("用戶存在");
else Console.WriteLine("用戶不存在");
if (two.UpdateUserPwd(newPwd, one.oldPwd)) Console.WriteLine("密碼修改成功");
else Console.WriteLine("密碼修改失敗");
}
}
// 未來切換 MySQL 只需新增實作類別
// public class MysqlUserOperation : IUserOperation { ... }
}
IUserOperation two = new SqlUserOperation();:介面型別參考指向實作類別實例,實現多型。MysqlUserOperation 實作同介面,上層邏輯完全不用動。interface IC : IA, IB { }| 場景 | 建議 |
|---|---|
| 定義跨類別層級的能力契約 | 介面 |
| 提供部分預設實作、共享欄位/狀態 | 抽象類別 |
| 需要多重實作組合 | 介面 (C# 單一類別繼承) |
| 版本演進需預設實作 (C# 8.0+) | 介面 default 方法 |