【问题标题】:Methods not working? [duplicate]方法不起作用? [复制]
【发布时间】:2017-12-01 03:04:08
【问题描述】:

这是我遇到了一些麻烦的代码块:

using System;
namespace TestProgram {
    class Test {
        static void Main() {
            int number = 10;
            MultiplyByTen(number);
            Console.WriteLine(number);
            Console.ReadKey(true);
        }
        static public void MultiplyByTen(int num) {
            num *= 10;
        }
    }
}

当我运行这段代码时,我得到的是 10 而不是 100。我的问题是:为什么会发生这种情况以及如何解决? 感谢您的帮助。

【问题讨论】:

标签: c#


【解决方案1】:

问题是,当变量编号进入方法 MultiplyByTen 时,值被复制,而您在其中修改的变量实际上是副本,所以原始没有改变。
试试这个:

 public static void MultiplyByTen(ref int num) 
 {
     num *= 10;
 }

但请记住,您还必须使用 ref 关键字来调用它。

static void Main() 
{
    int number = 10;
    MultiplyByTen(ref number);//Notice the ref keyword here
    Console.WriteLine(number);
    Console.ReadKey(true);
}

我建议您也检查一下:Passing Objects By Reference or Value in C#

【讨论】:

  • 我比我更喜欢你的回答。
【解决方案2】:

您需要将值返回给函数并将返回的值分配给数字。

  static void Main()
    {
        int number = 10;
        number = MultiplyByTen(number);
        Console.WriteLine(number);
        Console.ReadKey(true);
    }
    static public int MultiplyByTen(int num)
    {
        return num *= 10;
    }

【讨论】:

    【解决方案3】:

    使用你的实现:

    using System;
    namespace TestProgram {
        class Test {
            static void Main() {
                int number = 10;
                //MultiplyByTen(number);
                //Console.WriteLine(number);
                Console.WriteLine(MultiplyByTen(number));
                Console.ReadKey(true);
            }
            static public int MultiplyByTen(int num) {
                return num *= 10;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2020-08-17
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多