【问题标题】:I have n number of voice commands which is converted to string and then based on the command the execution takes place [duplicate]我有 n 个语音命令,它们被转换为字符串,然后根据命令执行 [重复]
【发布时间】:2018-08-09 11:40:34
【问题描述】:

但问题是我最终编写了一个 Switch 案例,导致每个命令有 n 个案例。我该如何避免呢? c#中的代码

例子:

switch ()
{
 case "Open File":
  //do something;
  break;
 case "Change color":
 //do something;
 break;
 .
 .
 .
 case n:
 // do smething;
 break;

}

【问题讨论】:

  • 到底是什么问题?你想避免什么?根据您提供给我们的 [少量] 信息,切换听起来很合理。
  • 如果你有很多这样的开关......你可以考虑使用工厂模式
  • @rory.ap: 有200多条命令,不值得写200个case。这就是我要避免的。此外,命令可以是任意长度,它不遵循特定模式
  • 那么您需要考虑编写专门的类来处理命令和/或命令类别。使用建议的@Ctznkane525 之类的工厂模式。 C# 是一种面向对象的编程语言,所以好好利用它吧。
  • 如何使用接口,例如。 ICommand,它提供了一个方法'Execute()'?然后,您可以通过调用 ICommand.Execute(); 来避免整个开关/案例;还是我完全偏离了轨道?

标签: c#


【解决方案1】:

您可以像这样将每个命令包装在自己的处理程序中:

public interface ICommandHandler
{
    string HandlesCommand { get; }
    void Execute();
}

public class OpenFileCommandHandler : ICommandHandler
{
    public string HandlesCommand => "Open File";
    public void Execute()
    {
        Console.WriteLine("Open File");
    }
}

public class ChangeColorCommandHandler : ICommandHandler
{
    public string HandlesCommand => "Change Color";
    public void Execute()
    {
        Console.WriteLine("Change color");
    }
}

如果你有一个 IoC 容器,你通常可以通过请求 IEnumerable<ICommandHandler> 来注入一个类中的所有处理程序。如果你没有 IoC 容器,你可以像这样将所有的处理程序放在一个数组中

private ICommandHandler[] _commandHandlers = {new OpenFileCommandHandler(), new ChangeColorCommandHandler()};

然后你可以找到一个命令的所有处理程序并像这样执行它们

var command = "Open File";
var handlers = _commandHandlers.Where(c => c.HandlesCommand == command);
foreach (var handler in handlers)
{
    handler.Execute();
}

这还有一个好处是您可以在不更改任何现有代码的情况下添加新的命令处理程序。

【讨论】:

  • 谢谢你的回答,我试试看。
猜你喜欢
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
相关资源
最近更新 更多