C# 数据类型与数据结构详解
一、基本数据类型(值类型)
1. 数值类型
整数类型:
byte(0-255, 1字节)short(-32,768~32,767, 2字节)int(-2.1亿~2.1亿, 4字节) → 最常用long(极大整数, 8字节)
浮点类型:
float(7位精度, 4字节) → 后缀加f,如3.14fdouble(15-16位精度, 8字节) → 默认小数类型decimal(28-29位精度, 16字节) → 财务计算专用
2. 其他值类型
bool:true/falsechar:单个Unicode字符(如'A')DateTime:日期时间(如DateTime.Now)enum:枚举类型(自定义值集合)
二、引用类型
1. 核心引用类型
string:不可变字符串(特殊引用类型,表现类似值类型)object:所有类型的基类dynamic:运行时类型检查class:自定义类
2. 数组
csharp
int[] numbers = new int[5]; // 一维数组
int[,] matrix = new int[2,3]; // 二维数组
string[] names = { "Alice", "Bob" }; // 初始化三、常用数据结构(System.Collections)
1. 线性结构
List<T>:动态数组(最常用)
csharpvar list = new List<int> { 1, 2, 3 }; list.Add(4);LinkedList<T>:双向链表
csharpvar linkedList = new LinkedList<string>(); linkedList.AddLast("First");Queue<T>:先进先出队列
csharpvar queue = new Queue<int>(); queue.Enqueue(1); // 入队 int first = queue.Dequeue(); // 出队Stack<T>:后进先出栈
csharpvar stack = new Stack<string>(); stack.Push("A"); // 压栈 string top = stack.Pop(); // 弹栈
2. 键值对结构
Dictionary<TKey,TValue>:哈希表字典
csharpvar dict = new Dictionary<string, int>(); dict["age"] = 25; // 添加/修改SortedDictionary<TKey,TValue>:基于二叉搜索树的排序字典
HashSet<T>:唯一值集合
csharpvar set = new HashSet<int> { 1, 2, 2 }; // 实际存储{1, 2}
3. 不可变集合(System.Collections.Immutable)
- 线程安全且不可修改:csharp
var immutableList = ImmutableList.Create(1, 2, 3); var newList = immutableList.Add(4); // 返回新集合
四、特殊数据结构
1. 元组(Tuple)
csharp
// 值元组(轻量级)
var point = (X: 10, Y: 20);
Console.WriteLine(point.X);
// 命名元组
Tuple<int, string> person = Tuple.Create(1, "Alice");2. 记录类型(Record)
csharp
public record Person(string Name, int Age);
var p1 = new Person("Alice", 25);3. 可空类型
csharp
int? nullableInt = null; // 等同于Nullable<int>五、选择指南
| 场景 | 推荐数据结构 |
|---|---|
| 需要快速随机访问 | List<T>/数组 |
| 频繁插入删除 | LinkedList<T> |
| 先进先出处理 | Queue<T> |
| 后进先出处理 | Stack<T> |
| 键值查找 | Dictionary<TKey,TValue> |
| 唯一值存储 | HashSet<T> |
| 线程安全操作 | 并发集合/不可变集合 |
六、性能对比
查找效率:
- 字典(O(1)) > 排序集合(O(log n)) > 列表(O(n))
内存开销:
- 数组 < List < LinkedList
- 值类型(栈内存) < 引用类型(堆内存)
使用建议:
- 数据量小(<100项):选择最易读的结构
- 数据量大:根据操作类型选择最优结构
以上结构都位于System.Collections和System.Collections.Generic命名空间,使用时需添加相应引用。