首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 方法參數進階:params 參數陣列、ref 與 out 差異詳解

     編輯:關於C語言

params 參數陣列

允許呼叫端傳入可變數量引數,內部接收為陣列:


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 vs out

特性refout
呼叫端初始化必須先指派不需初始化
方法內讀取可讀取初始值讀取前必須指派 (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);
}

C# 7+ 新語法


// out 變數宣告內嵌
GetValue(out int c); // c 直接可用

// ref 傳回與 ref 區域變數 (進階)
ref int Find(ref int[] arr, Func pred) { ... }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved