非泛型介面(IEnumerable、ICollection…)已標記過時,泛型版提供型別安全、效能(值類型免裝箱)、語意清晰。C++ 開發者注意:C# 泛型在執行期實例化,JIT 共享程式碼,避免 C++ 模板的程式碼膨脹。
| 介面 | 用途 | 關鍵成員 |
|---|---|---|
IEnumerable<T> | 支援 foreach 迭代 | GetEnumerator() |
IEnumerator<T> | 迭代器本體 | Current、MoveNext()、Reset() |
ICollection<T> | 集合基礎契約 | Count、Add/Remove/Clear、CopyTo、IsReadOnly |
IList<T> | 索引存取、有序集合 | this[int]、Insert/RemoveAt、IndexOf |
IDictionary<TKey,TValue> | 鍵值對集合 | this[TKey]、Keys/Values、ContainsKey |
IComparer<T> | 外部比較器 | Compare(T,T) |
IComparable<T> | 內建比較 | CompareTo(T) |
public class ListBoxTest : IEnumerable<string> {
private string[] _items = new string[8];
private int _count = 0;
public IEnumerator<string> GetEnumerator() {
for (int i = 0; i < _count; i++)
yield return _items[i]; // 編譯器自動產生狀態機
}
// 非泛型 IEnumerable 顯式實作(介面繼承關係要求)
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void Add(string s) => _items[_count++] = s;
public string this[int i] { get => _items[i]; set => _items[i] = value; }
}
IEnumerator<T> 的巢狀類別,封裝狀態(索引、this 指標)。MoveNext 執行到下一個 yield return 即暫停,下次繼續。var lb = new ListBoxTest("Hello", "World");
lb.Add("Who"); lb.Add("Is"); lb.Add("John"); lb.Add("Galt");
lb[1] = "Universe";
foreach (var s in lb) Console.WriteLine($"Value: {s}");
// Value: Hello
// Value: Universe
// Value: Who
// Value: Is
// Value: John
// Value: Galt
// Value:
// Value:
IEnumerable<T> → IEnumerable
↑
ICollection<T> → ICollection
↑
IList<T> → IList
↑
IDictionary<TKey,TValue> → IDictionary
實作 IList<T> 即自動滿足所有上層介面契約。
IEnumerable<T>、IReadOnlyList<T>),保留變更實作彈性。IReadOnlyCollection<T> / IReadOnlyList<T>(.NET 4.5+)。yield return,手寫 IEnumerator 易出錯且冗長。