
- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案I/O
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
csharp_methods.htm
廣告