简化使用if的多个if语句(string.contains()) [英] Simplify multiple if statements that use if (string.contains())

查看:1245
本文介绍了简化使用if的多个if语句(string.contains())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个个人助理程序,我有一个名为input_parse()的方法,它查看输入字符串并检查与伪代码看起来像这样的命令对应的单词。

I am working on a personal assistant program and I have a method called input_parse() which looks at the input string and checks for words that correspond to "commands" the pseudo code looks like this.

if (input.contains("argA")
   {//execute command A}
if (input.contains("argB") && input.contains("argC"))
   {//execute command B}

是否有一种更简单的方法来解决这个问题,可能是使用字符串数组的命令,然后根据参数索引使用switch语句?

is there a simpler way to tackle this problem perhaps with a string array of commands and then use a switch statement for the commands based on the index of the argument?

推荐答案

您可以创建一个字典,其中值将是您的命令,键可以是您的字符串(arg名称)。

You can create a Dictionary where the value will be your command and the key can be your string (arg name).

var myCommands = new Dictionary<string, Action>();
myCommands.Add("argA", new Action(() => Console.WriteLine("arga was passed")));
myCommands.Add("argB", new Action(() => Console.WriteLine("argb was passed")));

比你可以调用你的命令迭代字典的键。因此,如果传递了argA和argB,则将调用两个命令。

Than you can invoke your commands iterating through the keys of the dictionary. So if both argA and argB are passed both commands will be invoked.

foreach (var key in myCommands.Keys)
{
  if (input.Contains(key))
  {
    myCommands[key]();
  }
}

这是最简单的方法,你不需要创建任何类结构或类似的东西。适用于简单的控制台应用。

This is the easiest way, you don't need to create any class structure or anything like that. Perfect for simple console app.

编辑

要交叉匹配参数你可以定义以下字典

To cross match the parameters you can have the following Dictionary defined.

var myCommands new Dictionary<Func<string, bool>, Action>>();
myCommands.Add(new Func<string, bool>(i => i.Contains("argA")),new Action(() => Console.WriteLine("arga was passed"));
myCommands.Add(new Func<string, bool>(i => i.Contains("argB")),new Action(() => Console.WriteLine("arga was passed"));
myCommands.Add(new Func<string, bool>(i => i.Contains("argB") && e.Contains("argA")),new Action(() => Console.WriteLine("arga & argb was passed"));



foreach (var key in myCommands.Keys)
{
   if (key(input))
   {
      myCommands[key]();
   }
}

这篇关于简化使用if的多个if语句(string.contains())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆