通过过程传递变量以进行切换

时间:2018-11-13 17:43:35

标签: c# cmd menu

我试图弄清楚如何在numberRequest情况下使用switch中的整数,然后继续通过Addition过程使用它们。我是否需要对变量进行不同的范围划分?我可以通过某种方式互相传递变量吗?

class Program
{

    static void Main(string[] args)
    {
        int input;
        input = int.Parse(Console.ReadLine());
        switch (input)
        {
            case 1:
                numberRequest();
                int result = Addition(firstNum, secondNum);
                Console.Write(result);
                Console.ReadKey();
                break;
        }
    }

    static int Addition(int x, int y)
    {
        int result = x + y;
        return result;
    }

    static void numberRequest()
    {
        int firstNum;
        int secondNum;
        Console.SetCursorPosition(1, 7);
        Console.Write("Enter the first number:  ");
        firstNum = int.Parse(Console.ReadLine());
        Console.SetCursorPosition(1, 8);
        Console.Write("Enter the second number: ");
        secondNum = int.Parse(Console.ReadLine());
    }
}

2 个答案:

答案 0 :(得分:0)

创建一个类似的类:

class TwoNumbers
{
   public int First;
   public int Second;
}

然后更改numberRequest()以返回TwoNumbers而不是void:

static TwoNumbersnumberRequest()
{
    int firstNum;
    int secondNum;
    Console.SetCursorPosition(1, 7);
    Console.Write("Enter the first number:  ");
    firstNum = int.Parse(Console.ReadLine());
    Console.SetCursorPosition(1, 8);
    Console.Write("Enter the second number: ");
    secondNum = int.Parse(Console.ReadLine());
    return new TwoNumbers() { First = firstNum, Second = secondNum };
}

最后,在Main中:

…
case 1:
            TwoNumbers nums = numberRequest();
            int result = Addition(nums.First, nums.Second);

答案 1 :(得分:0)

firstNumsecondNum是仅存在的局部变量,只能通过numberRequest()函数进行访问。

有几种方法可以解决此问题。一种是使它们成为类成员变量。或者您可以让函数返回2个变量。我只会调用该函数两次。

static int numberRequest(string prompt, int left, int top)
{
    int num;
    // Loop until user enters valid input
    while (true) {
        Console.SetCursorPosition(left, top);
        Console.Write(prompt);
        if (int.TryParse(Console.ReadLine(), out num)) {
            return num;
        }
    }
}

然后在main中输入

static void Main(string[] args)
{
    int input;
    input = int.Parse(Console.ReadLine());
    switch (input)
    {
        case 1:
            int firstNum = numberRequest("Enter the first number:  ", 1, 8);
            int secondNum = numberRequest("Enter the second number:  ", 2, 8);
            int result = Addition(firstNum, secondNum);
            Console.Write(result);
            Console.ReadKey();
            break;
    }
}