允許呼叫端傳入可變數量引數,內部接收為陣列:
static int Sum(params int[] numbers)
{
int sum = 0;
foreach (int n in numbers) sum += n;
return sum;
}
Sum(1, 2, 3); // 6
Sum(1, 2, 3, 4, 5); // 15
Sum(new[] { 10, 20 }); // 30 (也可傳陣列)
限制:只能有一個 params 參數,且必須是最後一個參數。
| 特性 | ref | out |
|---|---|---|
| 呼叫端初始化 | 必須先指派 | 不需初始化 |
| 方法內讀取 | 可讀取初始值 | 讀取前必須指派 (CS0269) |
| 方法內指派 | 可選 | 強制指派 (所有路徑) |
| 用途 | 雙向資料流 | 單向輸出 |
// ref:引用傳遞,可修改原變數
static void Square(ref int x) => x *= x;
// out:輸出參數,方法必須指派
static void GetValue(out int x) => x = 100;
static void Main()
{
int a = 9;
Square(ref a); // a = 81
Console.WriteLine(a);
int b;
GetValue(out b); // b = 100
Console.WriteLine(b);
}
// out 變數宣告內嵌
GetValue(out int c); // c 直接可用
// ref 傳回與 ref 區域變數 (進階)
ref int Find(ref int[] arr, Func pred) { ... }