Skip to content

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.14f
    • double (15-16位精度, 8字节) → 默认小数类型
    • decimal (28-29位精度, 16字节) → 财务计算专用

2. 其他值类型

  • bool:true/false
  • char:单个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>:动态数组(最常用)

    csharp
    var list = new List<int> { 1, 2, 3 };
    list.Add(4);
  • LinkedList<T>:双向链表

    csharp
    var linkedList = new LinkedList<string>();
    linkedList.AddLast("First");
  • Queue<T>:先进先出队列

    csharp
    var queue = new Queue<int>();
    queue.Enqueue(1); // 入队
    int first = queue.Dequeue(); // 出队
  • Stack<T>:后进先出栈

    csharp
    var stack = new Stack<string>();
    stack.Push("A"); // 压栈
    string top = stack.Pop(); // 弹栈

2. 键值对结构

  • Dictionary<TKey,TValue>:哈希表字典

    csharp
    var dict = new Dictionary<string, int>();
    dict["age"] = 25; // 添加/修改
  • SortedDictionary<TKey,TValue>:基于二叉搜索树的排序字典

  • HashSet<T>:唯一值集合

    csharp
    var 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>
线程安全操作并发集合/不可变集合

六、性能对比

  1. 查找效率

    • 字典(O(1)) > 排序集合(O(log n)) > 列表(O(n))
  2. 内存开销

    • 数组 < List < LinkedList
    • 值类型(栈内存) < 引用类型(堆内存)
  3. 使用建议

    • 数据量小(<100项):选择最易读的结构
    • 数据量大:根据操作类型选择最优结构

以上结构都位于System.CollectionsSystem.Collections.Generic命名空间,使用时需添加相应引用。

✨ 网站运行时间: 3年11月15天 ❤️ 道阻且长,行则将至 - 微信号: heikedreamer