c# - 重构长 switch 语句

标签 c# .net refactoring switch-statement

我是用 c# 编写的程序,您可以通过口述命令进行控制,所以现在我有一个很长的 switch 语句。有点像

switch (command)

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

等等

几乎所有情况都只调用一个方法,方法不在一个类中而是分布在多个类中。所以问题是,我如何才能将此开关重构为更优雅的方式?

最佳答案

您可以这样做来重构您的 switch 语句:

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

这种方法的主要优点是您可以在运行时更改“开关”。

关于c# - 重构长 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20586041/

相关文章:

c# - 如何像在 Objective-C 2.0 中那样在 C# 中获取可选的接口(interface)方法实现?

asp.net - 将 HTML5 占位符文本添加到文本框 .net

c# - 如何使用 try-catch-finally 重构代码

database - 在生产中重构数据库的最佳实践?

c# - Visual Studio : How to properly build and specify the configurations and platforms for x64 and x86

c# - INSTALLLEVEL 不安装功能

.net - XmlSerializer 是否可以支持循环引用?

ruby-on-rails - Rails : Refactoring, View ,助手 : how does it all go together?

c# - 如何使用使用 Microsoft 增强型 RSA 和 AES 加密提供程序的证书请求创建自签名证书

c# - 更改 WPF 用户控件对另一个用户控件的可见性(登录)