IEnumerator
→ IEnumerable (GetEnumerator)
→ ICollection (Count, CopyTo, SyncRoot)
→ IList (Indexer, Add, Remove, Insert, Contains...)
| 介面 | 核心成員 | 語義 | 典型實現 |
|---|---|---|---|
| IEnumerator | Current, MoveNext(), Reset() | 逐個遍歷游標 | 內部實現 |
| IEnumerable | GetEnumerator() | 可被 foreach 遍歷 | 所有集合 |
| ICollection | Count, IsSynchronized, SyncRoot, CopyTo() | 有大小、可複製到數組、線程同步 | Array, List, HashSet |
| IList | Indexer, Add, Insert, Remove, IndexOf, IsFixedSize, IsReadOnly | 有序、可索引、可增刪改 | List, ArrayList |
bool ProcessItems(ICollection items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
if (items.Count == 0) return false; // O(1) 判斷,無需遍歷
foreach (var item in items) { /* ... */ }
return true;
}
理由:比 IEnumerable 多 Count 屬性,語義更精確(集合而非序列),避免多次枚舉陷阱。
void ModifyList(IList list)
{
list.Add(newItem);
list.RemoveAt(0);
var item = list[2];
}
ICollection 或 IReadOnlyCollection<T> (.NET 4.5+)IList 或 IList<T>IList 兼容性最好,調用者可向下轉型為 ICollection/IEnumerableIEnumerable<T> → ICollection<T> → IList<T>
IReadOnlyCollection<T> → IReadOnlyList<T> // 僅讀場景首選
掌握 IEnumerable → ICollection → IList 漸進式介面體系,根據「最小接口原則」選型:參數盡量寬(基類介面),返回盡量窄(具體介面)。.NET 2.0+ 專案首選泛型版本,獲得類型安全與效能雙重收益。