How to implement custom command line & execution

后端 未结 1 460
梦如初夏
梦如初夏 2021-01-23 23:29

I\'m trying to build a custom commandline for my app, i have several basic commands, and i simply use bunch of \"if\" statements to check what the command is. currently it looks

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 23:32

    You could stuff all commands into a Dictionary; if you can live with all commands having the same return type.

    I have used string and set up a few commands.

    I make use of the params keyword to avoid the ugly new object[] on each call.

    You still need to cast the arguments, unless you can make them all one type. (Which may actually be not such a bad idea, as they all come from an input string..)

    Here is an example:

    public delegate string cmdDel(params object[] args);
    
    Dictionary cmd = new Dictionary();
    

    Add a few functions:

    cmd.Add("clear", cmd_clear);
    cmd.Add("exit", cmd_exit);
    cmd.Add("add", cmd_add);
    cmd.Add("log", cmd_log);
    

    With these bodies:

    public string cmd_clear(params object[] args)
    {
        return "cleared";
    }
    
    public string cmd_exit(params object[] args)
    {
        return "exit";
    }
    
    public string cmd_add(params object[] args)
    {
        return ((int)args[0] + (int)args[1]).ToString();
    }
    
    public string cmd_log(params object[] args)
    {
        StringBuilder log = new StringBuilder();
        foreach (object a in args) log.Append(a.ToString() + " ");
        return log.ToString(); 
    }
    

    And test:

    Console.WriteLine(cmd["clear"]());
    Console.WriteLine(cmd["add"]( 23, 42));
    Console.WriteLine(cmd["log"]( 23, "+" + 42, "=", cmd["add"]( 23, 42) ));
    Console.WriteLine(cmd["exit"]());
    

    cleared

    65

    23 + 42 = 65

    exit

    Of course you still need to use (at least) as many lines for setup as you have commands. And also need to do a similar amount of error checking.

    But the command processing part can get pretty simple.

    0 讨论(0)
提交回复
热议问题