| 實值型別 | 參考型別 | |
|---|---|---|
| 儲存內容 | 資料本身 | 指向堆積物件的參考 (指標) |
| 預設傳遞 (ByVal) | **複製資料** → 方法內修改不影響原值 | **複製參考** → 方法內可修改物件內容,但無法替換原參考指向 |
| ref/out/in 傳遞 (ByRef) | 傳遞**變數別名** → 可修改原變數值 | 傳遞**參考的參考** → 可替換原參考指向新物件 |
void Square(int x) { x *= x; Console.WriteLine($"方法內: {x}"); } // 修改副本
int n = 5;
Console.WriteLine($"呼叫前: {n}"); // 5
Square(n);
Console.WriteLine($"呼叫後: {n}"); // 5 (未變)
void SquareRef(ref int x) { x *= x; Console.WriteLine($"方法內: {x}"); }
int n = 5;
SquareRef(ref n);
Console.WriteLine($"呼叫後: {n}"); // 25 (原值被修改)
bool TryParse(string s, out int result) {
return int.TryParse(s, out result); // 編譯器強制賦值
}
void ReadOnly(in int x) {
// x = 10; // 編譯錯誤:不可修改
Console.WriteLine(x);
}
// 優點:避免大型結構體複製開銷,同時保證不可變性
void ChangeArray(int[] arr) {
arr[0] = 999; // 修改物件內容 ✅ 影響原陣列
arr = new int[5]; // 替換區域參考 ❌ 不影響原變數
}
int[] a = {1, 2, 3};
ChangeArray(a);
Console.WriteLine(a[0]); // 999 (內容被改)
Console.WriteLine(a.Length); // 3 (參考未換)
void ReplaceArray(ref int[] arr) {
arr = new int[] { -1, -2, -3 }; // 替換原變數指向 ✅
}
int[] a = {1, 2, 3};
ReplaceArray(ref a);
Console.WriteLine(string.Join(",", a)); // -1,-2,-3 (原變數已指向新陣列)
// 實值型別
void Swap(ref T a, ref T b) where T : struct {
T temp = a; a = b; b = temp;
}
// 參考型別 (字串、類別)
void SwapRef(ref T a, ref T b) where T : class {
T temp = a; a = b; b = temp;
}
class Person : ICloneable {
public string Name;
public Address Addr; // 參考型別
// 淺拷貝 (MemberwiseClone) - 共用 Address 物件
public object ShallowClone() => MemberwiseClone();
// 深拷貝 - 遞歸複製所有參考物件
public object DeepClone() {
var clone = (Person)MemberwiseClone();
clone.Name = string.Copy(Name); // string 不變其實無需複製
clone.Addr = (Address)Addr.Clone(); // Address 需實作 ICloneable
return clone;
}
}
class Address : ICloneable {
public string City;
public object Clone() => MemberwiseClone(); // 此處無巢狀引用,淺拷貝即深拷貝
}
in 避免複製。ref (雙向) 或 out (單向輸出)。ValueTuple 回傳多值或 ref struct (C# 7.2+)。C# 參數傳遞本質是**「傳遞什麼」**:實值型別傳資料副本,參考型別傳參考副本。ref/out/in 只是在呼叫端與被呼叫端之間建立**別名關係**。徹底理解這一點,配合「實值 vs 參考」二維分析,所有傳遞行為皆可推導,無需死記硬背。