一、C# 类型体系总览
C# 所有类型最终都属于两大分类:
- 值类型(Value Type)
- 引用类型(Reference Type)
所有类型都继承自
object(
System.Object)。
二、值类型 vs 引用类型(核心区别)
1. 定义
- 值类型:数据直接存在栈上,变量本身就是数据。
- 引用类型:数据存在堆上,变量只是指向堆的地址(引用)。
2. 典型类型
值类型
- 基本类型:
int, long, float, double, bool, char - 枚举
enum - 结构体
struct - 可空值类型
int?
引用类型
- 字符串
string - 数组
int[] - 类
class - 接口
interface - 委托
delegate - 集合
List<T>,Dictionary<T,K>
3. 赋值行为
- 值类型赋值 → 复制一份数据,两个变量互不影响。
- 引用类型赋值 → 复制地址,两个变量指向同一份数据。
4. 内存与空值
- 值类型:不能为 null(除非用可空类型)
- 引用类型:默认是 null,不指向任何对象
三、可空类型(Nullable Type)
1. 作用
让值类型也能表示
null(比如数据库字段、前端传参可能为空)。
2. 语法
int? a = null; // 简写
Nullable<int> b = null; // 完整写法
3. 常用操作
int? num = null;
// 判断是否有值
if (num.HasValue) { ... }
// 获取值(空会报错)
int val = num.Value;
// 安全获取:空则给默认值
int safe = num ?? 0;
4. 空合并运算符 ??
int result = num ?? 100;
// 如果 num 是 null → 用 100
5. 空条件运算符 ?.(引用类型常用)
string s = null;
int len = s?.Length ?? 0;
// 不报错,直接返回 0
四、泛型(Generic)
1. 什么是泛型?
让类 / 方法 / 接口可以不预先指定具体类型,而是在使用时才指定。
2. 优点
- 代码复用
- 类型安全(不会乱传类型)
- 避免装箱拆箱(性能更高)
3. 语法
// 泛型类
public class MyList<T>
{
public void Add(T item) { }
}
// 使用
var list = new MyList<int>();
list.Add(10);
4. 泛型约束(限制 T 是什么类型)
where T : class // 必须是引用类型
where T : struct // 必须是值类型
where T : new() // 必须有无参构造
where T : 基类/接口 // 必须继承/实现
5. 泛型方法
T GetMax<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
五、C# 常用集合(最实用清单)
集合就是存放多个数据的容器,C# 提供了非常完善的泛型集合。
1. List<T> 动态数组
最常用、最万能的集合。
List<int> list = new List<int>();
list.Add(1);
list.AddRange(new[] {2,3});
list.RemoveAt(0);
int count = list.Count;
2. Dictionary<TKey, TValue> 键值对
根据键快速查找值,O (1) 速度。
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "张三";
dict.Add(2, "李四");
string name = dict[1];
3. HashSet<T> 不重复集合
自动去重,无索引、无顺序。
HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(1); // 不会重复
4. Queue<T> 队列
先进先出 FIFO。
Queue<int> q = new Queue<int>();
q.Enqueue(1);
int first = q.Dequeue();
5. Stack<T> 栈
先进后出 LIFO。
Stack<int> stack = new Stack<int>();
stack.Push(1);
int top = stack.Pop();
6. 数组 T[]
固定长度,性能最高。
int[] arr = new int[5];
六、核心知识点速记表
表格
| 特性 | 值类型 | 引用类型 |
|---|---|---|
| 存储 | 栈(Stack) | 堆(Heap) |
| 赋值 | 复制数据 | 复制地址 |
| null | 不支持(除非可空) | 默认为 null |
| 典型类型 | int、bool、struct | string、class、List、数组 |
| 方法传递 | 传值(副本) | 传引用(原对象) |
总结
- 值类型存数据,引用类型存地址,赋值行为完全不同。
- 可空类型
?让值类型可以为 null,配合??做安全取值。 - 泛型
<T>实现类型安全、代码复用、高性能。 - 日常开发优先用:
List<T>、Dictionary<TKey,TValue>。
文章摘自:https://www.cnblogs.com/chuansheng/p/19907996
