2011-01-05 53 views
6

我不确定这个问题是否已在别处得到解答,我似乎无法通过谷歌找到任何不是“Hello World”示例的内容......我使用C# .NET 4.0。'高级'控制台应用程序

我想开发一个控制台应用程序,它将打开,显示文本,然后等待用户输入命令,其中命令将运行特定的业务逻辑。

例如:如果用户打开应用程序并键入“帮助”,我想显示一些语句等等等等。我不知道如何编写用于用户输入的'事件处理程序'。

希望这是有道理的。任何帮助将非常感激! 干杯。

+2

代码的简单应用程序,说:“错误的命令”,不管什么类型的用户。然后发布你的代码,并提出更具体的问题。 – Jon 2011-01-05 14:40:32

+0

我肯定会,但我真的没有任何代码,因为我不知道从哪里开始... – keynesiancross 2011-01-05 14:45:51

回答

21

你需要几个步骤来实现这一点,但它不应该那么难。首先,你需要某种解析器来解析你写的东西。要阅读每个命令只需使用var command = Console.ReadLine(),然后解析该行。并执行命令......主要逻辑应该有一个基地寻找这个(排序):

public static void Main(string[] args) 
{ 
    var exit = false; 
    while(exit == false) 
    { 
     Console.WriteLine(); 
     Console.WriteLine("Enter command (help to display help): "); 
     var command = Parser.Parse(Console.ReadLine()); 
     exit = command.Execute(); 
    } 
} 

排序的,你很可能改变这种状况要复杂的多。

Parser和命令的代码是那种直截了当:

public interface ICommand 
{ 
    bool Execute(); 
} 

public class ExitCommand : ICommand 
{ 
    public bool Execute() 
    { 
     return true; 
    } 
} 

public static Class Parser 
{ 
    public static ICommand Parse(string commandString) { 
     // Parse your string and create Command object 
     var commandParts = commandString.Split(' ').ToList(); 
     var commandName = commandParts[0]; 
     var args = commandParts.Skip(1).ToList(); // the arguments is after the command 
     switch(commandName) 
     { 
      // Create command based on CommandName (and maybe arguments) 
      case "exit": return new ExitCommand(); 
       . 
       . 
       . 
       . 
     } 
    } 
} 
+1

非常感谢,这绝对是我在寻找的东西 – keynesiancross 2011-01-05 14:44:22

+0

对不起,界面是如何工作的这种情况?我没有使用接口,所以这可能是我的问题... – keynesiancross 2011-01-05 14:50:40

+0

接口只是指定角色对象应该具有哪种方法,并且可以定义几个不同的继承自接口的对象,让你的解析器为你创建这些对象,你可以将接口改变为你想要的,我只是用一个简单的'Execute'来完成,如果程序应该退出就返回'true',我可以用一个简单的命令来更新,样本 – 2011-01-05 14:57:09

0

这很简单,只需使用Console.WriteLineConsole.ReadLine()方法即可。从ReadLine中获得一个字符串。你可能会有一个可怕的if语句来验证这个反对已知/预期的输入。最好是有一个查询表。最复杂的将是编写一个解析器。这实际上取决于输入的复杂程度。

+0

但是使用Console.ReadLine()方法,那么如何编码不同的答案等排列呢?例如Console.ReadLine(),if(Console.ReadLine()==“help){} etc etc – keynesiancross 2011-01-05 14:42:16

0

Console.WriteLineConsole.ReadLineConsole.ReadKey是你的朋友。 ReadLine和ReadKey等待用户输入。 string[] args将包含所有参数,例如“帮助”。该数组是通过用空格分隔命令行参数来创建的。

0
switch (Console.ReadLine()) 
{ 
    case "Help": 
     // print help 
     break; 

    case "Other Command": 
     // do other command 
     break; 

    // etc. 

    default: 
     Console.WriteLine("Bad Command"); 
     break; 
} 

如果你正在寻找能够解析对他们有其他的东西像参数的命令,例如“操纵file.txt的”,那么这不会单独工作。但是,例如,您可以使用String.Split将输入分隔为一个命令和参数。

0

这很简单,但可能会满足您的需求。

// somewhere to store the input 
string userInput=""; 

// loop until the exit command comes in. 
while (userInput != "exit") 
{ 
    // display a prompt 
    Console.Write("> "); 
    // get the input 
    userInput = Console.ReadLine().ToLower(); 

    // Branch based on the input 
    switch (userInput) 
    { 
     case "exit": 
      break; 

     case "help": 
     { 
      DisplayHelp(); 
      break; 
     } 

     case "option1": 
     { 
      DoOption1(); 
      break; 
     } 

     // Give the user every opportunity to invoke your help system :) 
     default: 
     { 
      Console.WriteLine ("\"{0}\" is not a recognized command. Type \"help\" for options.", userInput); 
      break; 
     } 
    } 
} 
1

样本:

static void Main(string[] args) 
    { 
     Console.WriteLine("Welcome to test console app, type help to get some help!"); 

     while (true) 
     { 
      string input = Console.ReadLine(); 

      int commandEndIndex = input.IndexOf(' '); 

      string command = string.Empty; 
      string commandParameters = string.Empty; 

      if (commandEndIndex > -1) 
      { 
       command = input.Substring(0, commandEndIndex); 
       commandParameters = input.Substring(commandEndIndex + 1, input.Length - commandEndIndex - 1); 
      } 
      else 
      { 
       command = input; 
      } 

      command = command.ToUpper(); 

      switch (command) 
      { 
       case "EXIT": 
        { 
         return; 
        } 
       case "HELP": 
        { 
         Console.WriteLine("- enter EXIT to exit this application"); 
         Console.WriteLine("- enter CLS to clear the screen"); 
         Console.WriteLine("- enter FORECOLOR value to change text fore color (sample: FORECOLOR Red) "); 
         Console.WriteLine("- enter BACKCOLOR value to change text back color (sample: FORECOLOR Green) "); 
         break; 
        } 
       case "CLS": 
        { 
         Console.Clear(); 
         break; 
        } 

       case "FORECOLOR": 
        { 
         try 
         { 
          Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), commandParameters); 
         } 
         catch 
         { 
          Console.WriteLine("!!! Parameter not valid"); 
         } 

         break; 
        } 
       case "BACKCOLOR": 
        { 
         try 
         { 
          Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), commandParameters); 
         } 
         catch 
         { 
          Console.WriteLine("!!! Parameter not valid"); 
         } 

         break; 
        } 
       default: 
        { 
         Console.WriteLine("!!! Bad command"); 
         break; 
        } 
      } 
     } 
    } 
+1

这不是一个好的设计,因为你的功能是做所有的工作。你应该分工,所以每个部分都有一个责任。 – 2011-01-05 15:06:41

+0

我同意这一点,但我发现他正在寻找他可以学习的代码,但并不太复杂。你是正确的,逻辑应该分开。最后,你和我的结果都是一样的。 – HABJAN 2011-01-05 15:12:58

+1

它最终的结果肯定是一样的,但我认为我的解决方案不是那么复杂,重要的是你要学会如何以正确的方式做事......尽管我可能不适合每个人但设计是你应该考虑的事情。我甚至认为我的解决方案比较容易,因为当你阅读它时它更“流利”,如果你不需要它们,你可以跳过所有的细节。在高层次上,只读,读取命令,解析命令并最后执行命令。也就是说,您可以跳过命令解析和执行方式的细节。 – 2011-01-05 15:22:45

1

我知道这是一个老问题,但我正在寻找一个答案了。我无法找到一个简单的,所以我建立了InteractivePrompt。它的格式为NuGet Package,您可以轻松扩展GitHub上的代码。它还具有当前会话的历史记录。

在讨论的功能可以以这种方式实现与InteractivePrompt:

static string Help(string strCmd) 
{ 
    // ... logic 
    return "Help text"; 
} 
static string OtherMethod(string strCmd) 
{ 
    // ... more logic 
    return "Other method"; 
} 
static void Main(string[] args) 
{ 
    var prompt = "> "; 
    var startupMsg = "BizLogic Interpreter"; 
    InteractivePrompt.Run(
     ((strCmd, listCmd) => 
     { 
      string result; 
      switch (strCmd.ToLower()) 
      { 
       case "help": 
        result = Help(strCmd); 
        break; 
       case "othermethod": 
        result = OtherMethod(strCmd); 
        break; 
       default: 
        result = "I'm sorry, I don't recognize that command."; 
        break; 
      } 

      return result + Environment.NewLine; 
     }), prompt, startupMsg); 
}