C# 集合(Collection)
系统梳理 C# 集合框架的核心数据结构与接口统一性、非泛型 System.Collections 六大经典容器的装箱机制与用法对照,并给出向 System.Collections.Generic 泛型集合迁移的工程建议。
学完这一章,你能够
- 系统梳理 C# 集合框架的核心数据结构与接口统一性、非泛型 System.Collections 六大经典容器的装箱机制与用法对照,并给出向 System.Collections.Generic 泛型集合迁移的工程建议。
集合框架定位、常见数据结构与 Object 存储机制
集合(Collection)是 .NET 专门用于动态存储、检索与管理成组数据的类库体系,支持按位置索引、按键值查找以及动态扩容缩容。常见数据结构涵盖后进先出(LIFO)的栈、先进先出(FIFO)的队列、动态伸缩的有序列表以及基于散列快速查找的哈希表。大多数集合类实现了统一的标准接口(如 `IEnumerable`、`ICollection`、`IList`、`IDictionary`),因此在遍历、计数、增删等操作上具备高度一致的编程模型。
早期 .NET 1.x 提供的非泛型集合统一将元素以基类 `object`(`System.Object`)存储——由于 `int`、`string` 与自定义类型均继承自 `object`,单一容器可混装任意类型。但这也带来两项显著代价:值类型存入与取出时会反复发生装箱(Boxing)与拆箱(Unboxing)开销,且缺少编译期类型检查(错误转型只能在运行期抛 `InvalidCastException`)。因此现代 C# 工程应优先选用下一章介绍的 `System.Collections.Generic` 泛型集合(如 `List<T>`、`Dictionary<TKey, TValue>`、`Stack<T>`、`Queue<T>`)。
System.Collections 六大经典非抽象集合类对照
在 `System.Collections` 命名空间中(命名勘误提示:真实命名空间为复数形式的 `System.Collections`,而非单数 `System.Collection`),最经典的六类非泛型集合包括:动态数组 `ArrayList`(支持按索引任意位置增删、自动扩容与排序)、哈希表 `Hashtable`(按键值对快速散列定位)、排序列表 `SortedList`(始终按键排序,既可按键查找也可按整型下标访问,兼具数组与哈希表特性)、堆栈 `Stack`(`Push` 推入、`Pop` 弹出,严格遵循 LIFO)、队列 `Queue`(`Enqueue` 入队、`Dequeue` 出队,严格遵循 FIFO)以及点阵列 `BitArray`(以紧凑位数组表示任意长度的 `0`/`1` 布尔标志并支持按位逻辑运算)。下表汇总六大容器特征及对应现代泛型替代,全部六项均已在本机 `csc.exe` 实测核验。
System.Collections 六大常用非泛型集合类对照表
| 集合类 | 核心结构与典型用法 | 现代泛型替代与实测核验 |
|---|---|---|
| `ArrayList` | 可按整型下标索引的动态对象数组,支持任意位置 `Insert`/`Remove`、自动扩容、搜索与 `Sort` 排序 | 现代推荐 `List<T>`;实测排序插入删除得 `10,15,30` 及异构 `int`/`string` 存储 |
| `Hashtable` | 基于键哈希码组织键值对的无序集合,通过键快速读写与 `ContainsKey` 检索 | 现代推荐 `Dictionary<TKey, TValue>`;实测 `ContainsKey("k1")==True` 与索引取值 `"beta"` |
| `SortedList` | 按内部键自动维持升序的键值集合,同时支持按键检索(`sl[key]`)与按位置索引(`GetKey`/`GetByIndex`) | 现代推荐 `SortedList<TKey, TValue>`;实测乱序插入 `c/a/b` 后按 `a=1,b=2,c=3` 排序 |
| `Stack` | 后进先出(LIFO)对象集合,以 `Push` 入栈、`Pop` 出栈、`Peek` 仅查看栈顶 | 现代推荐 `Stack<T>`;实测依次压入 `A/B/C` 后 `Pop` 得 `C`、`Peek` 得 `B` |
| `Queue` | 先进先出(FIFO)对象集合,以 `Enqueue` 入队、`Dequeue` 出队、`Peek` 查看队首 | 现代推荐 `Queue<T>`;实测依次入队 `A/B/C` 后 `Dequeue` 得 `A`、`Peek` 得 `B` |
| `BitArray` | 紧凑管理动态长度二进制位(`true`/`false` 对应 `1`/`0`)的位集合,支持从 `0` 开始索引及 `And`/`Or`/`Not` 位运算 | 保留在 `System.Collections` 沿用;实测 `1010` 与 `1100` 按位与得 `1000`、按位或得 `1110` |
运行 csc.exe (.NET Framework 4.x) 六大 System.Collections 非泛型容器与泛型 List<int> 实测
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace CSharpCollectionLab
{
internal class Program
{
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: ArrayList dynamic resize, insert/remove/sort, and object storage
ArrayList al = new ArrayList();
al.Add(30);
al.Add(10);
al.Add(20);
al.Sort();
al.Insert(1, 15);
al.Remove(20);
List<string> alItems = new List<string>();
foreach (object item in al) alItems.Add(item.ToString());
ArrayList mixed = new ArrayList();
mixed.Add(42);
mixed.Add("text");
bool mixedTypes = (mixed[0] is int) && (mixed[1] is string) && (mixed[0] is object);
string actual1 = string.Format("sorted={0};mixed={1}", string.Join(",", alItems.ToArray()), mixedTypes);
cases.Add(CaseJson(
"arraylist_and_object_boxing",
"Verify ArrayList dynamic sort/insert/remove and non-generic object storage holding int and string",
"sorted=10,15,30;mixed=True",
actual1
));
// Case 2: Hashtable & SortedList (key and index access)
Hashtable ht = new Hashtable();
ht.Add("k1", "alpha");
ht["k2"] = "beta";
bool hasK1 = ht.ContainsKey("k1");
string htVal = (string)ht["k2"];
SortedList sl = new SortedList();
sl.Add("c", 3);
sl.Add("a", 1);
sl.Add("b", 2);
List<string> slOrder = new List<string>();
for (int i = 0; i < sl.Count; i++)
{
slOrder.Add(string.Format("{0}={1}", sl.GetKey(i), sl.GetByIndex(i)));
}
string actual2 = string.Format("ht={0}/{1};sl={2};byKey={3}", hasK1, htVal, string.Join(",", slOrder.ToArray()), sl["b"]);
cases.Add(CaseJson(
"hashtable_and_sortedlist",
"Verify Hashtable key lookup and SortedList key-sorted dual access by key and index",
"ht=True/beta;sl=a=1,b=2,c=3;byKey=2",
actual2
));
// Case 3: Stack (LIFO) & Queue (FIFO)
Stack st = new Stack();
st.Push("A");
st.Push("B");
st.Push("C");
string stOut = string.Format("{0},{1},{2}", st.Pop(), st.Peek(), st.Count);
Queue q = new Queue();
q.Enqueue("A");
q.Enqueue("B");
q.Enqueue("C");
string qOut = string.Format("{0},{1},{2}", q.Dequeue(), q.Peek(), q.Count);
cases.Add(CaseJson(
"stack_lifo_and_queue_fifo",
"Verify Stack LIFO Push/Pop/Peek and Queue FIFO Enqueue/Dequeue/Peek semantics",
"stack=C,B,2;queue=A,B,2",
string.Format("stack={0};queue={1}", stOut, qOut)
));
// Case 4: BitArray & Generic List<T> contrast
BitArray ba1 = new BitArray(new bool[] { true, false, true, false });
BitArray ba2 = new BitArray(new bool[] { true, true, false, false });
BitArray andRes = ((BitArray)ba1.Clone()).And(ba2);
BitArray orRes = ((BitArray)ba1.Clone()).Or(ba2);
StringBuilder sbAnd = new StringBuilder();
StringBuilder sbOr = new StringBuilder();
for (int i = 0; i < 4; i++)
{
sbAnd.Append(andRes[i] ? '1' : '0');
sbOr.Append(orRes[i] ? '1' : '0');
}
List<int> genList = new List<int> { 1, 2, 3 };
int sum = 0;
foreach (int v in genList) sum += v;
string actual4 = string.Format("and={0};or={1};genSum={2}", sbAnd.ToString(), sbOr.ToString(), sum);
cases.Add(CaseJson(
"bitarray_and_generic_contrast",
"Verify BitArray bitwise And/Or indexing and System.Collections.Generic.List<int> type-safe aggregation",
"and=1000;or=1110;genSum=6",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
- 核对 ArrayList 动态操作与 object 装箱、Hashtable/SortedList 键值与排序索引、Stack LIFO/Queue FIFO 及 BitArray 位运算与 List<int> 对比全部通过。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
当前源码 SHA256:4ee84e1e203ba0b893c7bbad4c4b78b896302063c4dbc84f1466178261678a2e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
ZIP SHA256:0f3fc3139433d56226a9642efb3ee38c42f2470f5fa2be14b8e8077716e01036
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在现代 C# 项目中推荐使用 `List<int>` 替代 `ArrayList`?`SortedList` 相比 `Hashtable` 的主要特性差异是什么?
展开参考解答
`ArrayList` 以 `object` 存储元素,存放 `int` 时会产生频繁装箱拆箱且缺乏编译期类型安全;`List<int>` 在 CLR 层直接以连续 `int[]` 存储,零装箱且编译期拦截类型错误。`SortedList` 始终按键维持升序并同时支持按键与按整型索引访问,而 `Hashtable` 是无序散列结构、仅支持按键访问。