使用 where 關鍵字限定型別參數需實作介面或繼承類別:
public class Dictionary<KeyType, ValType> where KeyType : IComparable
{
public void Add(KeyType key, ValType val)
{
switch (key.CompareTo(x)) { ... } // 無需轉型
}
}
public class Dictionary<KeyType, ValType>
where KeyType : IComparable, IEnumerable
where ValType : Customer
{ ... }
Stack<int>),效能最佳,無裝箱。Stack<string>、Stack<Customer> 共用程式碼)。Stack<int> s1 = new Stack<int>();
Stack<int> s2 = new Stack<int>(); // 重用同一具體型別
Stack<long> s3 = new Stack<long>(); // 另產生長整數版本