4

我希望我的控制台应用程序具有用户类型/help和控制台写入帮助等命令。我希望它像这样使用switch

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

我怎样才能做到这一点?提前致谢。

4

3 回答 3

12

根据您对勘误表答案的评论,您似乎希望继续循环,直到您被告知不要这样做,而不是在启动时从命令行获取输入。如果是这种情况,您需要在外部循环switch以保持运行。这是基于您上面所写内容的快速示例:

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;
           }
        }
     }
  }
}
于 2013-08-02T01:39:30.840 回答
0

这些方面的东西可能会起作用:

// 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]);
       }
   }
}

运行命令:cmdline1 ABC

输出:

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

我不再做 c#(任何)了,但希望这会有所帮助。

于 2013-08-02T01:27:28.117 回答
-1

存在诸如http://www.codeproject.com/Articles/63374/C-NET-Command-Line-Argument-Parser-Reloaded之类的 .open 源代码项目可以解决此问题。为什么要重新发明轮子?

于 2013-08-02T01:30:42.333 回答