核心差異速查表
| 特性 | ref | out |
| 呼叫前需初始化 | 是 | 否 |
| 方法內需指派值 | 否(可選) | 是(強制) |
| 用途 | 雙向傳遞/修改 | 單向輸出/回傳多值 |
程式碼示範
class TestApp
{
// out:離開方法前必須對所有 out 參數指派值
static void OutTest(out int x, out int y)
{
// int z = x; // 錯誤:x 尚未指派
x = 1;
y = 2;
}
// ref:參數需先初始化,方法內可讀可寫
static void RefTest(ref int x, ref int y)
{
x = 1;
y = x; // 可讀取 x 原值
}
public static void Main()
{
// out 範例
int a, b;
OutTest(out a, out b); // a=1, b=2
Console.WriteLine($"a={a}, b={b}");
int c = 11, d = 22;
OutTest(out c, out d); // 原值被覆寫
Console.WriteLine($"c={c}, d={d}");
// ref 範例
// int m, n; RefTest(ref m, ref n); // 編譯錯誤:未初始化
int o = 11, p = 22;
RefTest(ref o, ref p); // o=1, p=1
Console.WriteLine($"o={o}, p={p}");
}
}
進階補充
in (C# 7.2+):唯讀參考傳遞,結合 ref 效能與 out 安全性,適用大型結構體唯讀傳遞。
ref return / ref local:進階記憶體管理技巧,避免複製大型結構體。
- 編譯器對
ref/out 參數會產生不同的 IL 元數據([Out] 屬性),影響多語言互通性。