在C#编程中,数组、ArrayList、List、Dictionary都是常用的数据存储结构,它们各自有不同的设计目标和适用场景,下面分别介绍它们的用法与核心区别。

数组的用法
数组是C#中最基础的数据存储结构,它在声明时需要指定元素类型和长度,长度一旦确定就无法修改,所有元素必须是同一类型。
以下是数组的基本用法示例:
// 声明并初始化一个长度为3的int类型数组
int[] intArray = new int[3];
// 给数组元素赋值
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
// 遍历数组
foreach (int num in intArray)
{
Console.WriteLine(num);
}
// 也可以在声明时直接初始化
string[] strArray = { "张三", "李四", "王五" };ArrayList的用法
ArrayList位于System.Collections命名空间下,是非泛型集合,它可以存储任意类型的对象,长度可以动态扩容,不需要提前指定大小。
以下是ArrayList的基本用法示例:
using System.Collections;
// 创建ArrayList实例
ArrayList arrayList = new ArrayList();
// 添加不同类型的元素
arrayList.Add(100);
arrayList.Add("hello");
arrayList.Add(DateTime.Now);
// 访问元素,返回的是object类型,需要强制转换
int firstValue = (int)arrayList[0];
string secondValue = (string)arrayList[1];
// 遍历ArrayList
foreach (object item in arrayList)
{
Console.WriteLine(item);
}ArrayList的缺点是存储值类型时会产生装箱拆箱操作,会带来性能损耗,同时因为存储的是object类型,取数据时容易出现类型转换错误。
List的用法
List位于System.Collections.Generic命名空间下,是泛型集合,声明时需要指定元素类型,长度可以动态扩容,避免了ArrayList的装箱拆箱问题,类型安全更有保障。
以下是List的基本用法示例:
using System.Collections.Generic;
// 创建存储int类型的List
List<int> intList = new List<int>();
// 添加元素
intList.Add(1);
intList.Add(2);
intList.Add(3);
// 访问元素,不需要类型转换
int firstInt = intList[0];
// 移除元素
intList.Remove(2);
// 遍历List
foreach (int num in intList)
{
Console.WriteLine(num);
}Dictionary的用法
Dictionary同样是泛型集合,属于键值对结构,每个元素都包含一个唯一的键和对应的值,通过键可以快速检索到对应的值,查找效率很高。
以下是Dictionary的基本用法示例:
using System.Collections.Generic;
// 创建键为string、值为int的Dictionary
Dictionary<string, int> scoreDict = new Dictionary<string, int>();
// 添加键值对
scoreDict.Add("张三", 90);
scoreDict.Add("李四", 85);
scoreDict.Add("王五", 95);
// 通过键获取值
int zhangScore = scoreDict["张三"];
// 判断键是否存在
if (scoreDict.ContainsKey("李四"))
{
Console.WriteLine($"李四的成绩是{scoreDict["李四"]}");
}
// 遍历Dictionary
foreach (KeyValuePair<string, int> kvp in scoreDict)
{
Console.WriteLine($"姓名:{kvp.Key},成绩:{kvp.Value}");
}四者的核心区别
我们可以通过下表直观对比它们的差异:
| 数据结构 | 类型限制 | 长度是否可变 | 性能特点 | 适用场景 |
|---|---|---|---|---|
| 数组 | 同类型 | 不可变 | 性能最高,访问速度快 | 存储数量固定、类型统一的同类型数据 |
| ArrayList | 无限制,存object | 可变 | 有装箱拆箱开销,类型不安全 | 仅兼容旧版本代码,新项目不推荐使用 |
| List | 泛型,指定类型 | 可变 | 无装箱拆箱,类型安全,性能较好 | 存储同类型、数量不固定的集合数据,最常用 |
| Dictionary | 泛型,键和值都指定类型 | 可变 | 键值对查找,检索速度极快 | 需要通过唯一标识快速查找对应数据的场景 |
在实际开发中,如果没有特殊需求,优先选择List存储同类型集合数据,需要快速键值检索时使用Dictionary,尽量避免使用ArrayList,数组仅在数据量固定且追求极致性能时使用。
C#数组ArrayListListDictionary修改时间:2026-06-07 01:07:41