首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 集合類完整指南:介面體系、核心類別、泛型與非泛型對照、最佳實踐

     編輯:關於C語言

集合介面體系架構

所有集合實作 IEnumerable,支援 `foreach` 迭代。核心介面繼承鏈:


IEnumerable
  └─ ICollection (Count, CopyTo, IsSynchronized, SyncRoot)
       ├─ IList (索引存取、排序、插入刪除) → List, ArrayList
       └─ IDictionary (鍵值對) → Dictionary, Hashtable, SortedList

非泛型集合

類別實作介面特性適用場景
ArrayListIList, ICollection, IEnumerable動態陣列、Object 儲存、自動擴容 2倍舊專案相容、元素型別不固定
HashtableIDictionary, ICollection, IEnumerable雜湊表、鍵值對、執行緒安全(同步包裝)舊專案、需多執行緒讀取
SortedListIDictionary, ICollection, IEnumerable鍵排序、陣列實現、插入刪除 O(n)小資料量需排序字典
QueueICollection, IEnumerableFIFO 佇列、Enqueue/Dequeue訊息佇列、BFS
StackICollection, IEnumerableLIFO 堆疊、Push/Pop遞迴轉迭代、撤銷機制
BitArrayICollection, IEnumerable位元陣列、壓縮儲存旗標集合、位元運算

泛型集合 —— 首選

命名空間:System.Collections.Generic。優勢:型別安全、效能優於非泛型(避免裝箱/拆箱)、IntelliSense 完整。

泛型類別對應非泛型核心特性
List<T>ArrayList動態陣列、索引 O(1)、尾端增刪 O(1)
Dictionary<TKey, TValue>Hashtable雜湊表、查找/插入 O(1)、鍵唯一
SortedDictionary<TKey, TValue>SortedList紅黑樹、鍵排序、操作 O(log n)
SortedList<TKey, TValue>SortedList排序陣列、記憶體較省、插入 O(n)
Queue<T>QueueFIFO
Stack<T>StackLIFO
HashSet<T>—集合運算、去重、查找 O(1)
LinkedList<T>—雙向鏈表、中間增刪 O(1)
ConcurrentQueue<T> / ConcurrentDictionary<TKey,TValue>—執行緒安全、無鎖/細粒度鎖

強型別集合基類(舊版擴充點)

命名空間:System.Collections / System.Collections.Specialized

  • CollectionBase:非泛型 IList 實作基類,覆寫 `OnInsert/OnRemove/OnValidate` 等虛擬方法控制行為。
  • DictionaryBase:非泛型 IDictionary 實作基類。
  • ReadOnlyCollectionBase:唯讀包裝。
  • StringCollection、`StringDictionary`、`NameValueCollection`:字串專用集合。

現代開發請直接繼承 `Collection`、`KeyedCollection`、`ReadOnlyCollection`(在 `System.Collections.ObjectModel`),支援泛型且整合良好。

自訂集合實作 IEnumerable — 迭代器模式


public class MyIntCollection : IEnumerable {
    private int[] _data = { 1, 2, 3, 4, 5 };

    public IEnumerator GetEnumerator() {
        foreach (var x in _data) yield return x; // 編譯器自動生成狀態機
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // 非泛型介面顯式實作
}

// 使用
foreach (int n in new MyIntCollection()) Console.WriteLine(n);

效能選型速查表

需求推薦集合時間複雜度
頻繁索引存取、尾端增刪List<T>O(1) 索引、O(1) 尾端增刪
頻繁頭端/中間增刪LinkedList<T>O(1) 節點增刪(需節點參考)
鍵值快速查找Dictionary<TKey,TValue>O(1) 平均
鍵值需排序SortedDictionary<TKey,TValue>O(log n)
唯一值集合、集合運算HashSet<T>O(1) 查找
多執行緒佇列ConcurrentQueue<T>無鎖 Enqueue/TryDequeue
多執行緒字典ConcurrentDictionary<TKey,TValue>細粒度鎖、TryAdd/GetOrAdd
固定大小、唯讀Array / ReadOnlyCollection<T>最低記憶體、最快讀取

常見陷阱

  • foreach 中修改集合 → `InvalidOperationException`。解:先 `ToList()` 複本再刪,或用 `for` 逆向迴圈。
  • `Dictionary` 鍵為參考型別未正確實作 `GetHashCode/Equals` → 查找失效。解:實作 `IEquatable` 或提供 `IEqualityComparer`。
  • `List` 預設容量 0,頻繁 `Add` 觸發多次擴容複製。解:建構式指定 `new List(預估數量)`。
  • 非泛型 `ArrayList`/`Hashtable` 裝箱值型別 → 效能損耗、GC 壓力。解:全面改用泛型。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved