C#輸出方法

2019-10-16 23:17:45

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:
17
Enter the second value:
19
After method call, value of a : 17
After method call, value of b : 19