2013-08-02 108 views
2

我希望我的控制台应用程序具有诸如用户类型/help和控制台写入帮助的命令。我想用它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; 
} 

我该如何做到这一点?提前致谢。

+0

http://msdn.microsoft.com/en-us/library/vstudio/acy3edy3.aspx – squillman

+0

什么是与此代码的问题?你知道如何从'Console'读取一个字符串吗?这是你唯一缺少的东西,真的。那,以及围绕阅读和开关的循环。 – dasblinkenlight

+0

该代码是好的,但我不知道如何循环读取...新的c# – TheNeosrb

回答

6

根据您对errata's answer的评论,看起来您希望保持循环,直到您被告知不要这样做,而不是在启动时从命令行获取输入。如果是这种情况,您需要在switch之外循环以保持运行。这是基于一个快速的样品在你上面写道:

namespace ConsoleApplicationCSharp1 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     String command; 
     Boolean 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; 
      } 
     } 
    } 
    } 
} 
+0

就是这样。谢谢。 :) – TheNeosrb

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#多(有)了,但希望这有助于。

+0

这不是我在找...我希望用户输入控制台应用程序像'/ help'命令和控制台写其他命令... – TheNeosrb

相关问题