如何在 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.