Good time of day, gentlemen!

Help noob)

C # Code:

List<string> cmds = new List<string>(); { Console.Write("Hello>"); string line = Console.ReadLine(); switch (line) { case "print": { Console.WriteLine("Some print!"); } break; case "do": { SomeDo(); } break; case "clear": { Console.Clear(); } break; } } 

Question: How to catch exception, for example, if the user enters something not from the list? And as in this case or in case of successful execution of the command, return to Console.Write ("Hello>"); and continue to work?

    1 answer 1

    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).