是否可以返回先前返回的变量?

时间:2019-01-08 22:49:35

标签: c# methods

我正在为学校的一个项目进行某种猜猜游戏,但是在尝试返回以前返回的变量时遇到了问题。我不确定这是否是因为我尚未完成程序,还是我忽略了这一点。练习的重点是根据给定的参数生成和使用特定的方法,否则我将以不同的方式编写当前代码。

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

namespace AdvGuessNumber
{
    class Program
    {
        static void Main(string[] args)
        {
        }
        static string Input(string promptString)
        {
            Console.WriteLine(promptString);
            string inputString = Console.ReadLine();
            return inputString;
        }
        static int IntInput(string promptString)
        {
            bool isIntInput = false;
            Console.WriteLine(promptString);
            while (isIntInput == false){
                try
                {
                    Input(promptString);
                    inputInt = Convert.ToInt32(inputString);
                    isIntInput = true;
                }
                catch (FormatException)
                {
                    isIntInput = false;
                    continue;
                }
            }
            return inputInt;

        }
        static int GenerateNumber()
        {
            Random rand = new Random();
            int n = rand.Next(1, 100);
            return n;
        }
        static int GetGuess()
        {
            IntInput("Please enter an integer");
            return inputInt; //Trying to reference this from IntInput method


        }

    }
}

2 个答案:

答案 0 :(得分:5)

如果我正确理解了您的问题,则可以:

    static int GetGuess()
    {
        return IntInput("Please enter an integer");
    }

如果您需要在IntInput之后进行操作,可以先将值存储在变量中:

    static int GetGuess()
    {
        int value = IntInput("Please enter an integer");

        // Do something else here...

        return value;
    }

答案 1 :(得分:0)

如果您要问是否可以将返回值从一种方法传递给另一种方法,那么答案是肯定的!实际上,这正是recursion的工作方式,在这种情况下,方法将自行进行调用,直到达到已知条件为止,然后展开调用堆栈,并将返回值通过所有调用传递回,直到到达原始调用者为止。

这是一个示例,显示了一个方法如何在其操作中使用另一个方法的返回值。请注意,GetIntGetString条件内调用while,如果返回的字符串不能转换为int,则int.TryParse失败,并且while条件被反复执行(直到int.TryParse通过,之后变量result保存转换后的值):

static string GetString(string prompt)
{
    Console.Write(prompt);
    return Console.ReadLine(); // Return the result of the call to ReadLine directly
}

static int GetInt(string prompt)
{
    int result;
    while (!int.TryParse(GetString(prompt), out result)) ; // Empty while loop body
    return result;
}

这是另一个具有大量此类交互的示例:

public class Program
{
    private static readonly Random Rnd = new Random();

    private static string GetString(string prompt)
    {
        Console.Write(prompt);
        return Console.ReadLine();
    }

    private static int GetInt(string prompt)
    {
        int result;
        while (!int.TryParse(GetString(prompt), out result)) ;
        return result;
    }

    private static ConsoleKeyInfo GetKey(string prompt)
    {
        Console.Write(prompt);
        return Console.ReadKey();
    }

    private static bool PlayGame()
    {
        Console.Clear();
        Console.WriteLine("Guessing Game");
        Console.WriteLine("-------------");
        Console.WriteLine("I'm thinking of a number between 1 and 100.");
        Console.WriteLine("Let's see how many guesses it takes you to find it!\n");

        int input, guesses = 0, myNumber = Rnd.Next(1, 101);
        var message = "Enter your guess (or '0' to quit): ";

        for (input = GetInt(message);            // Initialize input to user's value
            input != 0 && input != myNumber;     // Iterate until they get it or enter 0
            input = GetInt(message), guesses++)  // Get a new value on each iteration
        {
            Console.WriteLine(input < myNumber ? "Too low!" : "Too high!");
        }

        Console.WriteLine(input == myNumber
            ? $"Correct! That took {guesses} guesses."
            : $"Sorry you didn't get it! The number was: {myNumber}.");

        // Here we call Equals directly on the result of GetString
        return GetString("\nDo you want to play again (y/n)? ")
            .Equals("y", StringComparison.OrdinalIgnoreCase);
    }

    private static void Main()
    {
        while (PlayGame()) ; // Empty while loop body - keeps looping until they say "no"
        GetKey("Done! Press any key to exit...");
    }
}