User input commands in Console application

让人想犯罪 __ 提交于 2020-02-02 06:25:49

问题


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;
}

How can I achieve this? Thanks in advance.


回答1:


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;
           }
        }
     }
  }
}



回答2:


Something along these lines might work:

// cmdline1.cs
// arguments: A B C
using System;
public class CommandLine
{
   public static void Main(string[] args)
   {
       // The Length property is used to obtain the length of the array. 
       // Notice that Length is a read-only property:
       Console.WriteLine("Number of command line parameters = {0}",
          args.Length);
       for(int i = 0; i < args.Length; i++)
       {
           Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
       }
   }
}

run the command: cmdline1 A B C

Output:

 Number of command line parameters = 3
    Arg[0] = [A]
    Arg[1] = [B]
    Arg[2] = [C]

I don't do c# much(any) anymore but hope this helps.




回答3:


There exist .open source projects like http://www.codeproject.com/Articles/63374/C-NET-Command-Line-Argument-Parser-Reloaded that take care of this. Why reinventing the wheel?



来源:https://stackoverflow.com/questions/18007246/user-input-commands-in-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!