控制台应用程序中的用户输入命令

控制台应用程序中的用户输入命令

问题描述:

我希望控制台应用程序具有用户类型 / help 之类的命令,并且控制台可以编写帮助。我希望它使用 switch 如:

I would like my console application to have commands like user types /help and console writes help. I would like it to use switch like:

switch (command)
{
    case "/help":
        Console.WriteLine("This should be help.");
        break;

    case "/version":
        Console.WriteLine("This should be version.");
        break;

    default:
        Console.WriteLine("Unknown Command " + command);
        break;
}

如何实现?

根据您对勘误表的答案,您似乎希望一直循环播放直到被告知不要循环播放,而不是在启动时从命令行获取输入。在这种情况下,您需要在开关之外循环以保持运行。这是一个基于您上面所写内容的快速示例:

Based on your comment to errata's answer, it appears you want to keep looping until you're told not to do so, instead of getting input from the command line at startup. If that's the case, you need to loop outside the switch to keep things running. Here's a quick sample based on what you wrote above:

namespace ConsoleApplicationCSharp1
{
  class Program
  {
    static void Main(string[] args)
    {
        string command;
        bool quitNow = false;
        while(!quitNow)
        {
           command = Console.ReadLine();
           switch (command)
           {
              case "/help":
                Console.WriteLine("This should be help.");
                 break;

               case "/version":
                 Console.WriteLine("This should be version.");
                 break;

                case "/quit":
                  quitNow = true;
                  break;

                default:
                  Console.WriteLine("Unknown Command " + command);
                  break;
           }
        }
     }
  }
}