引用參數 用於按引用傳遞自變量。 為引用參數傳遞的自變量必須是具有明確值的變量,並且在方法執行期間,引用參數指明的存儲位置與自變量相同。 引用參數使用 ref
修飾符進行聲明。
輸出參數 用於按引用傳遞自變量。 輸出參數與引用參數類似,不同之處在於,不要求向調用方提供的自變量顯式賦值。 輸出參數使用 out
修飾符進行聲明。 下面分別示例展示了如何使用 ref
out
關鍵字
using System; class RefExample { static void Swap(ref int x, ref int y) { int temp; temp = x; x = y; y = temp; } public static void SwapExample() { int i = 1, j = 2; Swap(ref i,ref j); Console.WriteLine($"{i}{j}"); } /*static void Main(string[] args) { SwapExample(); } */ } class OutExample { static void Divide(int x, int y,out int result,out int remainder) { result = x / y; remainder = x % y; } public static void OutUsage() { Divide(10, 3, out int res, out int rem); Console.WriteLine("{0} {1}", res, rem); } static void Main() { OutUsage(); RefExample.SwapExample(); } }