C#返回方法运行两次,但只调用一次

时间:2017-06-04 14:40:34

标签: c# methods return

我有这段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ReturnRandomNumber();
            Console.WriteLine("The number returned by ReturnRandomNumber was: " + ReturnRandomNumber());
            Console.ReadKey();
        }

        static int ReturnRandomNumber()
        {
            Console.WriteLine("This string should only be displayed once, since the method is only called once...");
            Random random = new Random();
            int numberToReturn = random.Next(1, 100);
            Console.WriteLine("So should this string...");

            return numberToReturn;
        }
    }
}

运行程序时的控制台输出是:

This string should only be displayed once, since the method is only called once...
So should this string...
This string should only be displayed once, since the method is only called once...
So should this string...
The number returned by ReturnRandomNumber was: [some random number between 1-100]

我只从我的main方法调用一次ReturnRandomNumber(),为什么它显然会运行两次?

如果我将ReturnRandomNumber设为void,并注释掉返回行,以及Main中的WriteLine,则该方法只运行一次,因此双重运行必须与返回有关 - 我只是不能找出什么?!

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您正在调用该方法两次。一旦进入主要的第一行:

ReturnRandomNumber();

你的写作声明第二次:

Console.WriteLine("The number returned by ReturnRandomNumber was: " + ReturnRandomNumber());

如果您只想调用该方法一次,并保留稍后显示的值,则应该执行以下操作:

static void Main(string[] args)
{
     int number = ReturnRandomNumber();
     Console.WriteLine("The number returned by ReturnRandomNumber was: " + number);
     Console.ReadKey();
}

返回方法只是意味着返回值。如果要使用返回的值,则需要将其保留以供日后使用 - 因此将结果存储在变量中。

在使用Random.Next(1,100)时,您已经完成了这项工作。 Random是一个类,Next是该类返回值的方法。

相关问题