C#中数组和动态数组
在C#中,数组和动态数组(通常指List<T>)是两种常用的集合类型,它们有以下几个主要区别:
1. 大小固定性
数组 (Array)
// 固定大小,创建后不能改变
int[] fixedArray = new int[5]; // 只能容纳5个元素
fixedArray[0] = 1;
fixedArray[1] = 2;
// fixedArray[5] = 6; // 运行时错误:索引越界
动态数组 (List)
// 动态大小,可自动扩容
List<int> dynamicList = new List<int>();
dynamicList.Add(1);
dynamicList.Add(2);
dynamicList.Add(3); // 自动调整容量
Console.WriteLine(dynamicList.Count); // 输出:3
2. 性能特点
数组
- 访问速度快:直接内存访问
- 内存开销小:没有额外的管理开销
- 添加/删除慢:需要重新创建数组
List
- 访问速度稍慢:有方法调用开销
- 内存开销较大:维护容量和计数信息
- 添加/删除灵活:自动处理扩容
3. 初始化方式
// 数组初始化
int[] array1 = new int[3];
int[] array2 = new int[] {1, 2, 3};
int[] array3 = {1, 2, 3};
// List初始化
List<int> list1 = new List<int>();
List<int> list2 = new List<int>() {1, 2, 3};
List<int> list3 = new List<int>(10); // 指定初始容量
4. 常用操作对比
// 数组操作
int[] numbers = new int[3];
numbers[0] = 10; // 赋值
int value = numbers[0]; // 读取
int length = numbers.Length; // 获取长度
// List操作
List<int> numberList = new List<int>();
numberList.Add(10); // 添加元素
numberList.Insert(0, 5); // 插入元素
numberList.Remove(10); // 删除元素
numberList.RemoveAt(0); // 按索引删除
int count = numberList.Count; // 元素数量
int capacity = numberList.Capacity; // 当前容量
5. 相互转换
// 数组转List
int[] array = {1, 2, 3};
List<int> listFromArray = array.ToList();
// List转数组
List<int> list = new List<int> {4, 5, 6};
int[] arrayFromList = list.ToArray();
6. 使用场景
适合使用数组的场景:
- 大小固定的集合
- 性能要求极高的场合
- 需要与低级API交互时
- 多维数据(如二维数组)
// 游戏中的地图网格
int[,] gameMap = new int[10, 10];
// 固定配置项
string[] weekDays = {"Mon", "Tue", "Wed", "Thu", "Fri"};
适合使用List的场景:
- 大小不确定的集合
- 需要频繁添加/删除元素
- 大多数业务逻辑场景
// 用户输入的数据
List<string> userInputs = new List<string>();
// 数据库查询结果
List<Customer> customers = new List<Customer>();
总结
| 特性 | 数组 | List |
|---|---|---|
| 大小 | 固定 | 动态 |
| 性能 | 访问快 | 操作灵活 |
| 内存 | 开销小 | 开销较大 |
| 使用 | 较简单 | 功能丰富 |
| 适用 | 固定大小数据 | 动态数据集合 |
在实际开发中,List<T>因其灵活性而更常用,但在性能敏感或大小固定的场景下,数组仍然是更好的选择。
8973

被折叠的 条评论
为什么被折叠?



