如何在不对每种情况使用 if 和 switch 语句的情况下重构链中的数百个条件?

How to refactor hundreds of conditions in chain without using if and switch statements for each cases?

我正在开发一个 AI 文本通信引擎,我想知道是否有人指出我 更有效方法的方向验证除 just 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
    }
}

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

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

谢谢,安迪

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

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

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