【问题标题】:How C# Method change the value of the parameter [duplicate]C#方法如何改变参数的值[重复]
【发布时间】:2021-02-27 19:21:12
【问题描述】:

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

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

非常感谢。

【问题讨论】:

  • MyFunc(x) 不会将x 传递给MyFunc,它只会传递x。见:stackoverflow.com/questions/5057267/…
  • 因为 x 是按值传递的,而不是按引用传递的,所以 Main 中的 x 永远不会改变
  • 谢谢大家。

标签: c# methods parameter-passing


【解决方案1】:

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


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    相关资源
    最近更新 更多