專案中定義多個繼承 ArrayList 的強型別集合 (如 UsersCollection、TimeEntriesCollection),皆實作 Sort() 方法。
QuickSort,要求元素實作 IComparable 或提供 IComparer。IComparable,可直接排序。IComparable 介面 (CompareTo 方法)。// 基本型別
ArrayList a = new ArrayList { 111, 2 };
a.Sort(); // 2, 111
// 自訂類別未實作 IComparable → 拋出 InvalidOperationException
ArrayList b = new ArrayList { new Class2("wo"), new Class2("ai") };
b.Sort(); // 錯誤
// 正確做法:實作 IComparable
public class Class2 : IComparable {
public string A { get; set; }
public int CompareTo(object obj) => A.CompareTo(((Class2)obj).A);
}
集合類別覆寫 Sort(),內部傳入自訂 IComparer 實作 (如依 UserName、Date 排序),**不修改實體類別**,符合開放封閉原則。