using System;
abstract class MyClass { }
class Program {
static void Main() {
// 編譯錯誤:Cannot create an instance of the abstract class
// MyClass obj = new MyClass();
Console.ReadKey();
}
}
using System;
abstract class Parent { }
class Child : Parent { }
class Program {
static void Main() {
Parent obj = new Child(); // 多型:父類別參考指向子類別實例
Console.WriteLine(obj.GetType().Name); // Child
Console.ReadKey();
}
}
| 維度 | 抽象類別 | 介面 |
|---|---|---|
| 多重實作 | 單一繼承 | 多重實作 |
| 成員類型 | 方法、屬性、欄位、建構函式、常數 | 方法、屬性、事件、索引子(C# 8.0+ 可有預設實作) |
| 存取修飾詞 | 完整支援 | 隱含 public |
| 共用狀態/邏輯 | 支援(欄位、非抽象方法) | 不支援(無狀態) |
| 版本演進 | 新增非抽象成員不破壞相容 | C# 8.0 前新增成員破壞相容 |
Animal → Dog/Cat)IFlyable/ISwimmable)interface IRepository {
T GetById(int id);
void Save(T entity);
}
abstract class RepositoryBase : IRepository {
protected abstract T FindById(int id); // 子類別實作細節
protected abstract void Persist(T entity);
public T GetById(int id) {
var entity = FindById(id);
if (entity == null) throw new KeyNotFoundException();
return entity;
}
public void Save(T entity) {
Validate(entity);
Persist(entity);
}
protected virtual void Validate(T entity) { } // 可選擇覆寫
}
class UserRepository : RepositoryBase {
protected override User FindById(int id) => /* DB 查詢 */;
protected override void Persist(User entity) => /* DB 寫入 */;
}
此模式結合抽象類別共用流程控制與介面定義契約,兼具彈性與複用性。