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

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

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

去年关闭。




Improve this question




我正在开发一个 AI 文本通信引擎,我想知道是否有人将我指向 的方向更有效的方法验证 以外的用户输入只是开关/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
    }
}
我应该补充一点,我有能力检查句子中的关键字。
我觉得由于所有输入都是字符串,并且它正在处理语言,这可能是唯一的方法,但如果有人有更好的方法,例如。接口(interface)、自定义类型、反射、线程或任何东西,然后我全神贯注。
谢谢,安迪

最佳答案

安迪!您可以与代表合作以实现这种灵 active 。委托(delegate)有点复杂,不如“直接”代码快,但它们有其值(value)。
在这里,我假设您的比较对象将始终是一个字符串(以及许多其他内容,如果此解决方案不符合您的需要,请发表评论以便我们进行处理)。

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

关于c# - 如何在不为每种情况使用 if 和 switch 语句的情况下重构链中的数百个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65908872/

相关文章:

javascript - 如何从 webbrowser C# 返回 javascript 函数值

PHP MySQL 插入文件,使用带有 OR 运算符的 IF 语句验证表单

c - 如果第一个条件通过,OR 中的第二个条件是否会执行?

java - 简化 Java IF-ELSE

c++ - 带有 QString 类型的 C++ 中的 switch/case 语句

c# - 异步消息发送Asp.net

C# 和 DotNetBrowser Ajax 请求不起作用

c# - Xamarin.Mac 模糊 SIGSEGV

c++ - Boost:创建一个返回变体的函数

sql - case when in where 子句 Postgresql