如何使用Polymorphysm简化重复的Swtich案例代码

时间:2019-06-25 19:18:17

标签: c# polymorphism

我想使用polymorphysm / interface简化Switch语句中的重复代码

public static class CommandProcessor
{
    public static string ProcessCommand(string input)
    {
        var args = input.Split();

        switch (args[0])
        {
            case "addcontact":
                var command = new AddContactCommand();
                return command.Execute(args);

            case "removecontact":
                var command1 = new RemoveContactCommand();
                return command1.Execute(args);

            case "updatecontact":
                var command2 = new UpdateContactCommand();
                return command2.Execute(args);

            case "search":
                var command3 = new SearchCommand();
                return command3.Execute(args);

            case "listcontacts":
                var command4 = new ListContactsCommand();
                return command4.Execute(args);


            default:
                return "Invalid command";
        }
    }
}

0 个答案:

没有答案