Usually they do something like this:
Dictionary<string, Action> commands = new Dictionary<string, Action>() { { "print", (Action)(() => Console.WriteLine("Some print!")) }, { "do", SomeDo }, { "clear", (Action)(() => Console.Clear) } }; while (true) { Console.Write(prompt); string input = Console.ReadLine(); if (commands.ContainsKey(input)) commands[input](); else Console.WriteLine("Unrecognized command: " + input); }
Perhaps you will need to provide for the presence of arguments among the teams.
For arguments, you can do something like this: replace Action
with Action<IEnumerable<string>>
.
Dictionary<string, Action<IEnumerable<string>>> commands = new Dictionary<string, Action<IEnumerable<string>>>() { { "print", MakeSimpleCommand(() => Console.WriteLine("Some print!")) }, { "do", SomeDo }, { "clear", MakeSimpleCommand(() => Console.Clear) } }; while (true) { Console.Write(prompt); string input = Console.ReadLine(); var tokens = SplitIntoTokens(input); var command = tokens.FirstOrDefault(); if (command == null) continue; if (commands.ContainsKey(command)) { try { commands[command](tokens.Skip(1)); } catch (Exception e) { Console.WriteLine("Execution failed: " + e.Message); } } else { Console.WriteLine("Unrecognized command: " + command); } } Action<IEnumerable<string>> MakeSimpleCommand(Action a) { return args => { if (args.Any()) throw new ArgumentException("this command doesn't support args"); a(); } } IEnumerable<string> SplitIntoTokens(string s) { // ΡΡΡ Π½Π°Π΄ΠΎ Π±Ρ ΡΡΠΎ-ΡΠΎ ΠΏΠΎΡ
ΠΈΡΡΠ΅Π΅, ΠΊΠ°ΠΊ ΠΌΠΈΠ½ΠΈΠΌΡΠΌ ΡΡΠΈΡΡΠ²Π°ΡΡ Π³ΡΡΠΏΠΏΠΈΡΠΎΠ²ΠΊΡ // ΠΊΠ°Π²ΡΡΠΊΠ°ΠΌΠΈ ΠΈ escape-ΡΠΈΠΌΠ²ΠΎΠ»Ρ return s.Split(null as char[], StringSplitOptions.RemoveEmptyEntries); }
If you want to implement the history and editing of the line more conveniently, look towards the implementation of readline in C # from one of the main Mono developers (you can simply plug it into the project, here is an example of its use).