“高级”控制台应用程序

发布于 2024-10-10 15:11:52 字数 254 浏览 9 评论 0原文

我不确定这个问题是否已在其他地方得到解答,而且我似乎无法通过 google 找到任何不是“Hello World”示例的内容...我正在使用 C# .NET 4.0 进行编码。

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

例如:如果用户打开应用程序并输入“help”,我想显示许多语句等。但我不确定如何为用户输入编写“事件处理程序”。

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

I'm not sure if this question has been answered elsewhere and I can't seem to find anything through google that isn't a "Hello World" example... I'm coding in C# .NET 4.0.

I'm trying to develop a console application that will open, display text, and then wait for the user to input commands, where the commands will run particular business logic.

For example: If the user opens the application and types "help", I want to display a number of statements etc etc. I'm not sure how to code the 'event handler' for user input though.

Hopefully this makes sense. Any help would be much appreciated!
Cheers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

梦里寻她 2024-10-17 15:11:52

您需要几个步骤才能实现这一目标,但这应该不那么难。首先,您需要某种解析器来解析您编写的内容。要读取每个命令,只需使用 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();
               .
               .
               .
               .
         }
    }
}

You need several steps to achieve this but it shouldn't be that hard. First you need some kind of parser that parses what you write. To read each command just use var command = Console.ReadLine(), and then parse that line. And execute the command... Main logic should have a base looking this (sort of):

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

Sort of, you could probably change that to be more complicated.

The code for the Parser and command is sort of straight forward:

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();
               .
               .
               .
               .
         }
    }
}
以可爱出名 2024-10-17 15:11:52

我知道这是一个老问题,但我也在寻找答案。但我无法找到一个简单的,所以我构建了 InteractivePrompt。它以 NuGet 包 的形式提供,您可以轻松扩展 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);
}

I know this is an old question, but I was searching for an answer too. I was unable to find a simple one though, so I built InteractivePrompt. It's available as a NuGet Package and you can easily extend the code which is on GitHub. It features a history for the current session also.

The functionality in the question could be implemented this way with 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);
}
探春 2024-10-17 15:11:52

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

This is easy enough, just use the Console.WriteLine and Console.ReadLine() methods. From the ReadLine you get a string. You could have a horrible if statement that validate this against known/expected inputs. Better would be to have a lookup table. Most sophisticated would be to write a parser. It really depends on how complex the inputs can be.

女中豪杰 2024-10-17 15:11:52

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

Console.WriteLine Console.ReadLine and Console.ReadKey are your friends. ReadLine and ReadKey waits for user input. The string[] args will have all of your parameters such as 'help' in them. The array is created by separating the command line arguments by spaces.

君勿笑 2024-10-17 15:11:52
switch (Console.ReadLine())
{
    case "Help":
        // print help
        break;

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

    // etc.

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

如果您要解析包含其他内容(例如参数)的命令,例如“manipulate file.txt”,那么仅此方法是行不通的。但是您可以使用 String.Split 将输入分隔为命令和参数。

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

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

    // etc.

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

If you're looking to parse commands that have other things in them like parameters, for example "manipulate file.txt" then this alone won't work. But you could for example use String.Split to separate the input into a command and arguments.

在巴黎塔顶看东京樱花 2024-10-17 15:11:52

样本:

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

A sample:

    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;
                    }
            }
        }
    }
z祗昰~ 2024-10-17 15:11:52

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

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

This is very simplistic, but might meet your needs.

// 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;
        }
    }
}
給妳壹絲溫柔 2024-10-17 15:11:52

有一个 C# nuget 包,名为 'ReadLine',作者为 'tornerdo'。语句 ReadLine.Read("prompt > "); 会在 CustomAutoCompletionHandler.PossibleAutoCompleteValues 中提供的选项中提示用户。

此外,您可以更改每个提示的 CustomAutoCompletionHandler.PossibleAutoCompleteValues。这确保用户可以从可用\支持的选项列表中选择一个选项。不易出错。

static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine(" Note! When it prompts, press <tab> to get the choices. Additionally, you can use type ahead search.");
    Console.ForegroundColor = ConsoleColor.White;

    // Register auto completion handler..
    ReadLine.AutoCompletionHandler = new CustomAutoCompletionHandler();

    CustomAutoCompletionHandler.PossibleAutoCompleteValues = new List<string> { "dev", "qa", "stg", "prd" };
    var env = CoverReadLine(ReadLine.Read("  Environment > "));
    Console.WriteLine($"Environment: {env}");
}

private static string CoverReadLine(string lineRead) => CustomAutoCompletionHandler.PossibleAutoCompleteValues.Any(x => x == lineRead) ? lineRead : throw new Exception($"InvalidChoice. Reason: No such option, '{lineRead}'");
        
public class CustomAutoCompletionHandler : IAutoCompleteHandler
{
    public static List<string> PossibleAutoCompleteValues = new List<string> { };

    // characters to start completion from
    public char[] Separators { get; set; } = new char[] { ' ', '.', '/' };

    // text - The current text entered in the console
    // index - The index of the terminal cursor within {text}
    public string[] GetSuggestions(string userText, int index)
    {
        var possibleValues = PossibleAutoCompleteValues.Where(x => x.StartsWith(userText, StringComparison.InvariantCultureIgnoreCase)).ToList();
        if (!possibleValues.Any()) possibleValues.Add("InvalidChoice");
        return possibleValues.ToArray();
    }
}

There is a C# nuget package called 'ReadLine' by 'tornerdo'. The statement ReadLine.Read(" prompt > "); prompts the user within options provided in CustomAutoCompletionHandler.PossibleAutoCompleteValues.

Additionally, you can change the CustomAutoCompletionHandler.PossibleAutoCompleteValues for each prompt. This ensures that the user get to choose an option from available\ supported list of options. Less error prone.

static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine(" Note! When it prompts, press <tab> to get the choices. Additionally, you can use type ahead search.");
    Console.ForegroundColor = ConsoleColor.White;

    // Register auto completion handler..
    ReadLine.AutoCompletionHandler = new CustomAutoCompletionHandler();

    CustomAutoCompletionHandler.PossibleAutoCompleteValues = new List<string> { "dev", "qa", "stg", "prd" };
    var env = CoverReadLine(ReadLine.Read("  Environment > "));
    Console.WriteLine(
quot;Environment: {env}");
}

private static string CoverReadLine(string lineRead) => CustomAutoCompletionHandler.PossibleAutoCompleteValues.Any(x => x == lineRead) ? lineRead : throw new Exception(
quot;InvalidChoice. Reason: No such option, '{lineRead}'");
        
public class CustomAutoCompletionHandler : IAutoCompleteHandler
{
    public static List<string> PossibleAutoCompleteValues = new List<string> { };

    // characters to start completion from
    public char[] Separators { get; set; } = new char[] { ' ', '.', '/' };

    // text - The current text entered in the console
    // index - The index of the terminal cursor within {text}
    public string[] GetSuggestions(string userText, int index)
    {
        var possibleValues = PossibleAutoCompleteValues.Where(x => x.StartsWith(userText, StringComparison.InvariantCultureIgnoreCase)).ToList();
        if (!possibleValues.Any()) possibleValues.Add("InvalidChoice");
        return possibleValues.ToArray();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文