Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm program in c# which you controlling by dictating command so now i have a long switch statement. Something like

switch (command)

{
    case "Show commands":
        ProgramCommans.ShowAllCommands();
        break;
    case "Close window":
        ControlCommands.CloseWindow();
        break;
    case "Switch window":
        ControlCommands.SwitchWindow();
        break;
}

and so on

Almost all cases call only one method, methods are not in one class they are distributed in many classes. So the question is, how i could refactor this switch to more elegant way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
183 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this to refactor your switch statement:

var commands = new Dictionary<string, Action>()
{
    { "Show commands", () => ProgramCommans.ShowAllCommands() },
    { "Close window", () => ControlCommands.CloseWindow() },
    { "Switch window", () => ControlCommands.SwitchWindow() },
};

if (commands.ContainsKey(command))
{
    commands[command].Invoke();
}

The main advantage to this approach is that you can change the "switch" at run-time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...