首页 > 解决方案 > C#方法如何改变参数的值

问题描述

我对下面的代码如何工作感到困惑。为什么输出不是 10 而是 5?

public class Program
{
    public  void MyFunc(int x){
        x = 10;
    }
    public void Main()
    {
        int x = 5;
        MyFunc(x);
        Console.WriteLine(x);
    }
}

非常感谢。

标签: c#methodsparameter-passing

解决方案


阅读“ref 关键字” 现在结果是 10


 public static void MyFunc(ref int x)
        {
            x = 10;
        }
        public static void Main()
        {
            int x = 5;
            MyFunc(ref x);
            Console.WriteLine(x);
        }


推荐阅读