由网友(→_→腦殘?過來)分享简介:我的程序中,你控制通过口述命令C#所以现在我有很长的switch语句。类似于I'm program in c# which you controlling by dictating command so now i have a long switch statement. Something likeswitch...
我的程序中,你控制通过口述命令C#所以现在我有很长的switch语句。类似于
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;
}
等
几乎所有的情况下调用只有一个方法,方法并不在一类它们分布在许多类。所以,问题是,我怎么能重构这个开关,更优雅的方式?
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?
推荐答案
您可以做到这一点重构你的switch语句:
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.
相关推荐
最新文章