在每次用户输入时都有一个控制台命令

问题描述 投票:0回答:1

我想让一个菜单命令在每一个用户输入时都能工作,基本上,用户能够通过输入在程序中移动。

string input = Console.ReadLine();
switch(input):
{
    case "Up":
        y++;
        Console.WriteLine("Moving up at x: " + x + ", y: " + y);
        break;
    case "Down":
        y--;
        Console.WriteLine("Moving down at x: " + x + ", y: " + y);
        break;
    case "Left":
        x--;
        Console.WriteLine("Moving left at x: " + x + ", y: " + y);
        break;
    case "Right":
        x++;
        Console.WriteLine("Moving right at x: " + x + ", y: " + y);
        break;
    default:
        Console.WriteLine("Standing still at x: " + x + ", y: " + y);
        break;
}

这将或多或少的当用户选择是移动。我想做的是一个菜单命令,每次写完都会打开一个菜单,而不用每次都放一个 "菜单 "的情况下(我不会把这个开关放在do while里面,因为我需要自定义每次移动)。有没有办法在整个程序执行过程中,每当用户给出一个特定的输入时,都能运行一段代码?

c# console-application
1个回答
0
投票

我看了你的问题第二遍,看来你只需要把这段代码提取到自己的方法中就可以了。一个简单的方法是直接调用 HandleDirectionalInput 的任何菜单方法。

public bool HandleDirectionalInput(string input)
{
    switch(input):
    {
        case "Up":
            y++;
            Console.WriteLine("Moving up at x: " + x + ", y: " + y);
            return true;
        case "Down":
            y--;
            Console.WriteLine("Moving down at x: " + x + ", y: " + y);
            return true;
        case "Left":
            x--;
            Console.WriteLine("Moving left at x: " + x + ", y: " + y);
            return true;
        case "Right":
            x++;
            Console.WriteLine("Moving right at x: " + x + ", y: " + y);
            return true;
    }
    return false;
}

所以你最终会得到这样的结果。

public void DoMainMenu()
{
    Console.WriteLine("some stuff here");
    string input = Console.ReadLine();
    if (!HandleDirectionalInput(input))
    {
        // do other main menu checks on input
    }
}

还有其他的方法可以做到这一点, 比如创建一个命令处理程序的列表,每个命令处理程序都可以轮流处理输入, 但这可能比你现在需要的要复杂得多.

© www.soinside.com 2019 - 2024. All rights reserved.