如何在 C# 中向方法傳遞引數?


接下來,讓我們看看如何在 C# 中按值傳遞引數以將引數傳遞給方法。在此機制中,當呼叫方法時,將為每個值引數建立一個新的儲存位置。

將實際引數的值複製到其中。因此,方法內部對引數所做的更改不會對實參產生任何影響。

以下是如何將引數傳遞給方法的示例 -

示例

 線上演示

using System;

namespace Demo {
   class NumberManipulator {
      public void swap(int x, int y) {
         int temp;
         temp = x;
         x = y;
         y = temp;
      }
      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();
         int a = 50;
         int b = 150;
         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);
         /* calling a function to swap the values */
         n.swap(a, b);
         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
         Console.ReadLine();
      }
   }
}

輸出

Before swap, value of a : 50
Before swap, value of b : 150
After swap, value of a : 50
After swap, value of b : 150

更新時間:20-Jun-2020

170 人瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.