Simplify multiple if statements that use if (string.contains())

后端 未结 3 1532
青春惊慌失措
青春惊慌失措 2021-01-26 10:20

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 ps

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-26 10:30

    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();
    myCommands.Add("argA", new Action(() => Console.WriteLine("arga was passed")));
    myCommands.Add("argB", new Action(() => Console.WriteLine("argb was passed")));
    

    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.

    EDIT

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

    var myCommands new Dictionary, Action>>();
    myCommands.Add(new Func(i => i.Contains("argA")),new Action(() => Console.WriteLine("arga was passed"));
    myCommands.Add(new Func(i => i.Contains("argB")),new Action(() => Console.WriteLine("arga was passed"));
    myCommands.Add(new Func(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]();
       }
    }
    

提交回复
热议问题