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

上一篇: C#方法 下一篇: C#可空類型(nullable)