2

Доброе время суток, господа!

Помогите нубу)

Код C#:

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

Вопрос: Как поймать exception, скажем, если пользователь вводит что-то не из перечня? И как в этом случае или в случае успешного выполнения команды вернуться к Console.Write("Hello>"); и продолжить работу?

1 ответ 1

7

Обычно делают как-то так:

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

Возможно, вам надо будет ещё предусмотреть наличие аргументов у команд.


Для аргументов можно сделать что-то наподобие такого: заменяем Action на 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);
}

Если вы хотите реализовать историю и редактирование строки более удобно, посмотрите в сторону реализации readline на C# от одного из главных разработчиков Mono (её можно просто подключить в проект, вот пример использования).

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.