// 僅能接受陣列
void LoadList(object[] items, ListBox lb) { ... }
// 使用 ICollection,支援陣列、List、資料庫結果等
void LoadList(ICollection items, ListBox lb) {
foreach (object o in items) lb.Items.Add(o.ToString());
}
介面鬆綁具體實作,提高複用性與測試性。
virtual/abstract,介面中可定義屬性private int _month;
[XmlAttribute("Month")]
public int Month { get => _month; set => _month = value; }
public delegate void OnGetLine(string line);
public class KeyboardProcessor {
public event OnGetLine OnLineReceived;
public void Run() {
string s;
while ((s = Console.ReadLine()) != "") {
OnLineReceived?.Invoke(s); // 多播自動支援多訂閱者
}
}
}
委派天然支援多播,降低耦合,無需定義介面。