C# 方法參數四種類型,以修飾詞區分:
| 類型 | 修飾詞 | 記憶體行為 | 初始化要求 |
|---|---|---|---|
| 值參數 | 無 | 複製值到新位置 | 呼叫端必須已指派 |
| 參考參數 | ref | 傳遞位址(別名) | 呼叫端必須已指派 |
| 輸出參數 | out | 傳遞位址(別名) | 方法內必須指派 |
| 參數陣列 | params | 封裝為陣列 | 呼叫端可給 0~N 引數 |
static void Swap(int x, int y) { int t=x; x=y; y=t; }
int i=1, j=2; Swap(i,j); // i=1, j=2 不變
static void Swap(ref int x, ref int y) { int t=x; x=y; y=t; }
int i=1, j=2; Swap(ref i, ref j); // i=2, j=1 成功
class A {
string s;
void F(ref string a, ref string b) { s="One"; a="Two"; b="Three"; }
void G() { F(ref s, ref s); } // s, a, b 三個參考指向同一記憶體
}
呼叫 G() 時,s、a、b 成為同一記憶體位置的別名,最後值為 "Three"。