.NET 集合框架以介面為核心,ICollection<T> 定義了集合的基本契約。本文實作演示泛型集合介面的標準用法,並深入解析 BitArray 進行高效位元組操作的特殊方法。
using System.Collections.ObjectModel;
ICollection<int> coll = new Collection<int>();
coll.Add(100); coll.Add(22); coll.Add(30);
foreach (int x in coll) Console.WriteLine(x); // 列舉
Console.WriteLine("Count: " + coll.Count); // 3
coll.Add(222);
coll.Remove(22); // 移除首個匹配項
Console.WriteLine("Count: " + coll.Count); // 3
Console.WriteLine("Contains 22: " + coll.Contains(22)); // False
int[] arr = new int[coll.Count];
coll.CopyTo(arr, 0); // 從索引 0 開始複製
for (int i = 0; i < coll.Count; i++)
Console.WriteLine($"arr[{i}]={arr[i]}, coll={coll.ElementAt(i)}");
CopyTo 是將集合內容批次轉為陣列的高效方式,適用於需隨機存取或傳遞給僅接受陣列的 API。
ICollection<string> strColl = new Collection<string>();
strColl.Add("the "); strColl.Add("people's ");
strColl.Add("republic "); strColl.Add("china ");
foreach (string s in strColl) Console.Write(s); // 輸出: the people's republic china
BitArray 以位元為單位儲存布林值,記憶體效率極高(32 個布林值僅佔 4 位元組)。支援邏輯運算與位元級存取。
BitArray bits = new BitArray(4); // 4 個位元,預設 false
bits[0] = false; bits[1] = true; bits[2] = true; bits[3] = false;
DisplayBits("Initial", bits);
// Initial[0]=False, Initial[1]=True, Initial[2]=True, Initial[3]=False
| 方法 | 功能 | 範例 |
|---|---|---|
And(BitArray) | 邏輯 AND,就地修改 | bits.And(mask) |
Or(BitArray) | 邏輯 OR,就地修改 | bits.Or(flag) |
Not() | 邏輯 NOT,就地修改 | bits.Not() |
Xor(BitArray) | 邏輯 XOR,就地修改 | bits.Xor(key) |
Get/Set(index, val) | 單一位元讀寫 | bits.Set(2, false) |
SetAll(val) | 全域設定 | bits.SetAll(true) |
Console.WriteLine("After Not():");
bits.Not();
DisplayBits("Not", bits);
// Not[0]=True, Not[1]=False, Not[2]=False, Not[3]=True
public static void DisplayBits(string name, BitArray ba)
{
for (int i = 0; i < ba.Count; i++)
Console.WriteLine($"{name}[{i}] = {ba[i]}");
}
bool 變數(如檔案屬性、權限掩碼)BitArray 非泛型、不可調整大小(建構時固定長度),但提供極佳的空間效率與位元運算性能。現代 .NET 亦可考慮 System.Collections.Immutable.BitArray 或 Vector<ulong> 進行 SIMD 加速。