將 Customer 替換為型別參數 T,完成輕量級泛型清單類別:
public class List<T> : CollectionBase
{
public T this[int index]
{
get { return (T)List[index]; }
set { List[index] = value; }
}
public int Add(T value) { return List.Add(value); }
}
語法:where T : constraint_type。例如要求實作 IDisposable 以配合 using 區塊:
public class List<T> : CollectionBase where T : IDisposable
{
// ...
}
約束類型可為:類別、介面、結構、無參公用建構函式 (new())、特定基底類別。
泛型設計目的:減少重複實作,僅變更資料型別。抽象資料結構 (佇列、堆疊、清單) 最適合泛型化。善用 System.Collections.Generic 現有泛型類別,轉換新資料結構為可重用泛型程式碼元素。