【问题标题】:How to refactor hundreds of conditions in chain without using if and switch statements for each cases? [closed]如何在不为每种情况使用 if 和 switch 语句的情况下重构链中的数百个条件? [关闭]
【发布时间】:2021-04-30 16:20:55
【问题描述】:

我正在开发一个 AI 文本通信引擎,我想知道是否有人指出我的方向是更有效的方法来验证用户输入而不是 只是 switch / if 语句。

这是它的基础:

void Update(){
    string s = Console.Read()s.ToLower();

    if (s == "c1"){
        // do 1
    }
    else if (s == "c2"){
        // do 2
    }

    ...

    else if (s == "c9342"){
        // do 9342
    }
}

我应该补充一下,我有能力检查句子中的关键字。

我觉得由于所有输入都是字符串,并且它正在处理语言,这可能是唯一的方法,但如果有人有更好的方法,例如。接口、自定义类型、反射、线程或任何东西,我都在听。

谢谢,安迪

【问题讨论】:

  • 方法有很多。我可能会使用预先填充的ternary search tree
  • 如果你需要帮助重构代码,你需要提供真实的代码,有真实的案例,不是所有的,但最小的看原理图,能够提供帮助,或者使用 codereview.stackexchange。 com。所以在这里,它是广泛的。系列 c1, c2, c3, c4, c5...c9342 是否以 +1 为增量?还有什么是do1,do2,do3 ...?方法 ?具有可提取参数的重复内部代码?还是完全不同的处理?否则,除了 if 和 switch,以及在某些方法和循环中使用参数分解之外,您还可以使用像 @AndreSantarosa 的答案公开的调度表。
  • 要添加到其他人,不要一直做.ToLower(),只要做.Equals(...., StringComparison.OrdinalIgnoreCase)

标签: c# if-statement switch-statement refactoring processing-efficiency


【解决方案1】:

安迪!您可以与代表合作以实现这种灵活性。委托有点复杂,速度不如“直接”代码,但它们有其价值。

在这里,我假设您的比较对象将始终是一个字符串(以及许多其他内容,如果此解决方案不符合您的需要,请留下评论,以便我们进行处理)。

// Create a dictionary where the key is your comparison string and
// the action is the method you want to run when this condition is matched
Dictionary<string, Action> ifs = new Dictionary<string,Action>()
{
    // Note that after the method name you should not put () 
    // otherwise you would be invoking this method instead of create a "pointer" 
    {"c1", ExecuteC1},
    {"c2", ExecuteC2},
    {"c9342", ExecuteC9342},
}

private void ExecuteC1()
{
    Console.WriteLine("c1");
}    

private void ExecuteC2()
{
    Console.WriteLine("c2");
}    

private void ExecuteC9342()
{
    Console.WriteLine("c9342");
}

public RunCondition(string condition)
{
   // Get the condition related value by its key and calls the method with 'Invoke()'
   ifs[condition].Invoke();
}    

【讨论】:

  • 感谢您将我的问题视为有效问题。尽管遵循了多年来我停止使用它的所有规则,但我在堆栈溢出方面遇到了如此可怕的运气。德尔盖特听起来像很棒的途径。我很欣赏这种洞察力,并且非常感谢您花时间帮助一位程序员寻求帮助。在提出问题并得到如此多的负面回应后,我总是很生气地离开这个网站。所以谢谢你。
  • @Triangle4Studios 通过不回答问题来帮助您,您正在剥夺自己获得更好和更短答案的潜力。在某些情况下,不到 10 行代码可能会取代数百行代码,甚至更多。但是,如果此答案符合您的需要,那很好。如果您有任何问题,请随时再次发布任何问题。
  • 很高兴帮助@Triangle4Studios =) 哦,如果您需要参数或返回类型,请使用 Func 而不是 Action
猜你喜欢
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多