值类型和引用类型※
这是 C#/.NET 中最重要的概念之一,决定了变量如何存储和传递数据。
值类型(Value Type)※
- 数据直接存储在栈/结构体内
- 赋值时复制数据(副本独立)
- 类型:int、float、bool、char、struct、enum
int a = 10;
int b = a; // b 是 a 的副本
b = 20;
Console.WriteLine(a); // 10(a 不受影响)
引用类型(Reference Type)※
- 变量存的是堆上的地址引用
- 赋值时复制引用(指向同一对象)
- 类型:class、string、数组、接口、委托
class Person { public int Age; }
Person p1 = new Person { Age = 10 };
Person p2 = p1; // p2 指向同一对象
p2.Age = 20;
Console.WriteLine(p1.Age); // 20(同一对象被改)
参数传递※
void Modify(int x) { x = 100; } // 值传递:外部不变
void Modify(ref int x) { x = 100; } // ref:外部改变
void Modify(out int x) { x = 100; } // out:必须赋值
特殊:string※
string 是引用类型但不可变(immutable),任何修改都创建新字符串,所以表现像值类型。