sbyte, byte, char, short, ushort, int, uint, long, ulong, float, double, decimal, bool、struct, enumstring, object, class, interface, delegate, array值型別預設傳值(複製)。加上 ref 或 out 後,方法直接操作原變數記憶體位址,效果等同 C 指標。
static void Main() {
int a = 5; int b;
SquareRef(ref a); // a 必須已初始化
SquareOut(out b); // b 無需初始化,方法內必指派
Console.WriteLine($"a={a}, b={b}"); // a=25, b=100
}
static void SquareRef(ref int x) { x = x * x; Console.WriteLine($"ref內 x={x}"); }
static void SquareOut(out int y) { y = 10; y = y * y; Console.WriteLine($"out內 y={y}"); }
輸出:
ref內 x=25
out內 y=100
a=25, b=100
| 特性 | ref | out |
|---|---|---|
| 呼叫端變數需初始化 | 是 | 否 |
| 方法內讀取參數前需指派 | 否 | 是 |
| 適用場景 | 雙向資料流 | 純輸出參數 |
下一篇將探討參考型別的複雜語義。