如何在Visual Studio的C#聊天机器人中实现Case.Contains功能?
实现C#聊天机器人的不区分大小写包含匹配功能
嘿,我懂你想要的效果——不区分大小写地检测用户输入是否包含指定短语,而不是原来switch语句的精确匹配。毕竟switch默认是严格的相等判断,没法直接实现包含式的匹配逻辑,咱们来调整代码解决这个问题:
首先,先明确核心方法:C#的string.Contains有一个重载方法,可以指定字符串比较规则,用来实现不区分大小写的包含检测:
chat.Contains("目标短语", StringComparison.OrdinalIgnoreCase)
用StringComparison.OrdinalIgnoreCase是最推荐的方式,它比把字符串转成小写/大写再比较更高效,还能避免不同语言文化带来的字符差异问题。
接下来,我们把你原来的switch逻辑替换成更适合的判断方式,这里给两种方案:
方案1:通用if-else写法(兼容所有C#版本)
这是最稳妥的写法,不管你用的是哪个版本的C#都能运行:
private void QuestionBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { // 建议Trim掉输入的前后空格,避免空格干扰匹配判断 string chat = QuestionBox.Text.Trim(); string utisateur = "Vous : "; string bot = "Robot : "; ChatBox.Items.Add(utisateur + chat); QuestionBox.Clear(); string reponseA = "I'm good thanks and you ?"; // 检测输入是否包含指定短语(不区分大小写) if (chat.Contains("How are you", StringComparison.OrdinalIgnoreCase) || chat.Contains("Are you ok ?", StringComparison.OrdinalIgnoreCase)) { ChatBox.Items.Add(bot + reponseA); } // 可以继续添加其他else if块处理更多问题 else if (chat.Contains("Hello", StringComparison.OrdinalIgnoreCase)) { ChatBox.Items.Add(bot + "Hello there!"); } // 默认回复,当没有匹配到任何规则时触发 else { ChatBox.Items.Add(bot + "Sorry, I don't get what you mean."); } } }
方案2:C# 9+ 模式匹配写法(更简洁)
如果你用的是C# 9及以上版本(对应Visual Studio 2019 16.8+),可以用带when子句的switch表达式,代码会更简洁:
private void QuestionBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { string chat = QuestionBox.Text.Trim(); string utisateur = "Vous : "; string bot = "Robot : "; ChatBox.Items.Add(utisateur + chat); QuestionBox.Clear(); string reponseA = "I'm good thanks and you ?"; // 用switch表达式匹配不同场景 var response = chat switch { string input when input.Contains("How are you", StringComparison.OrdinalIgnoreCase) || input.Contains("Are you ok ?", StringComparison.OrdinalIgnoreCase) => reponseA, string input when input.Contains("Hello", StringComparison.OrdinalIgnoreCase) => "Hello there!", _ => "Sorry, I don't understand that." }; ChatBox.Items.Add(bot + response); } }
补充说明:为什么原来的switch不行?
你原来的switch语句里,case只能是常量表达式,C# 9之前完全不支持带条件判断的case,C#9之后也需要搭配when子句才能实现;而且默认的case是精确匹配字符串,所以没法直接实现包含检测的需求。另外你原代码里的switch部分还有语法错误(比如ase "Hello how are you ?:的拼写和引号问题),换成上面的写法就能一并解决啦。
内容的提问来源于stack exchange,提问作者Juste
相关产品推荐
相关产品推荐

