桔子媛 发表于 2019-7-24 10:25:24

求解读这段代码

using System;
namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void swap(int x, int y)
      {
         int temp;
         
         temp = x; /* 保存 x 的值 */
         x = y;    /* 把 y 赋值给 x */
         y = temp; /* 把 temp 赋值给 y */
      }
   
      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* 局部变量定义 */
         int a = 100;
         int b = 200;
         
         Console.WriteLine("在交换之前,a 的值: {0}", a);
         Console.WriteLine("在交换之前,b 的值: {0}", b);
         
         /* 调用函数来交换值 */
         n.swap(a, b);
         
         Console.WriteLine("在交换之后,a 的值: {0}", a);
         Console.WriteLine("在交换之后,b 的值: {0}", b);
         
         Console.ReadLine();
      }
   }
}

在交换之前,a 的值:100
在交换之前,b 的值:200
在交换之后,a 的值:100
在交换之后,b 的值:200


为何交换之后a、b的值还是不变??

永恒的蓝色梦想 发表于 2019-8-4 12:14:18

围观一下,也不太懂……
是不是因为只是修改了局域变量里的值,而没有传递回来?

你曾经笑得无邪 发表于 2019-8-6 16:43:29

using System;
namespace CalculatorApplication
{
    class NumberManipulator
    {
      public void swap(ref int x,refint y)
      {
            int temp;

            temp = x; /* 保存 x 的值 */
            x = y;    /* 把 y 赋值给 x */
            y = temp; /* 把 temp 赋值给 y */
      }

      static void Main(string[] args)
      {
            NumberManipulator n = new NumberManipulator();
            /* 局部变量定义 */
            int a = 100;
            int b = 200;

            Console.WriteLine("在交换之前,a 的值: {0}", a);
            Console.WriteLine("在交换之前,b 的值: {0}", b);

            /* 调用函数来交换值 */
            n.swap(ref a, ref b);

            Console.WriteLine("在交换之后,a 的值: {0}", a);
            Console.WriteLine("在交换之后,b 的值: {0}", b);

            Console.ReadLine();
      }
    }
}

Geo_Modric 发表于 2019-8-8 22:52:07

函数调用时,你的代码中为按值传递,并未改变a ,b本身。
ref为按引用传递参数,3楼代码应该没问题。
页: [1]
查看完整版本: 求解读这段代码