C#按輸出參數傳遞
return語句可用於從函數返回僅有一個值。然而,使用輸出參數,可以從一個函數返回兩個值。輸出參數是相似的參考參數,隻是它們傳送數據的方法,而不是到它裡邊。
下麵的例子說明了這一點:
using System; namespace CalculatorApplication { class NumberManipulator { public void getValue(out int x ) { int temp = 5; x = temp; } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* local variable definition */ int a = 100; Console.WriteLine("Before method call, value of a : {0}", a); /* calling a function to get the value */ n.getValue(out a); Console.WriteLine("After method call, value of a : {0}", a); Console.ReadLine(); } } }
讓我們編譯和運行上麵的程序,這將產生以下結果:
Before method call, value of a : 100 After method call, value of a : 5
輸出參數中提供的變量不需要被分配一個值的方法調用。當需要從一個方法,通過該參數不分配一個初始值來將參數返回值的輸出參數是特彆有用的。看看下麵的例子中,理解這一點:
using System; namespace CalculatorApplication { class NumberManipulator { public void getValues(out int x, out int y ) { Console.WriteLine("Enter the first value: "); x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the second value: "); y = Convert.ToInt32(Console.ReadLine()); } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* local variable definition */ int a , b; /* calling a function to get the values */ n.getValues(out a, out b); Console.WriteLine("After method call, value of a : {0}", a); Console.WriteLine("After method call, value of b : {0}", b); Console.ReadLine(); } } }
當上述代碼被編譯和執行時,它產生了以下結果(根據用戶輸入):
Enter the first value: 7 Enter the second value: 8 After method call, value of a : 7 After method call, value of b : 8