如何实现自定义命令行&执行 [英] How to implement custom command line & execution

查看:24
本文介绍了如何实现自定义命令行&执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用程序构建一个自定义命令行,我有几个基本命令,我只是使用一堆if"语句来检查命令是什么.目前它看起来像这样

public void ExecuteCommand(){字符串输入 = ReadLine();//从输入中获取最后一个字符串布尔 isDone = false;//需要bool来检查命令是否执行,默认为false.匹配结果 = Regex.Match(input, @"([^s]+)");//获取命令名字符串 commandName = result.Value.ToLower();字符串值 = Regex.Match(输入,@"s(.*)").Value;//获取它的参数.目前在 ' ' 空格之后的所有内容.if (commandName == "close"){关闭();isDone = true;}//所以命令行是单独的窗口,appendedForm是主窗体.在其中执行一些功能.if (commandName == "exit"){appendedForm.Close();}if (commandName == "spoof"){appendedForm.Fn_Spoof();isDone = true;}if(commandName == "spoofstop"){appendedForm.Fn_StopCapture();isDone = true;}如果(命令名 == 扫描"){appendedForm.Fn_Scan();isDone = true;}如果(命令名 == 清除"){输出.文本 = "";WriteLine("控制台已清空.缓存为空.");//data_lines.Clear();isDone = true;}...}

基本上就是这样.我有一个 mainForm 和命令行表单.字符串输入被输入到命令行,然后我检查命令的名称并从 mainForm 执行一些函数.

我的问题是,实现此类事情的最佳方式是什么?我当然可以继续写一堆如果",但有些事情告诉我,这不是最好的方法.

我想过创建命令"类

 公共类命令{公共字符串名称;公共字符串描述;公共布尔具有参数;命令(){}}

并将所有命令存储在某种数组中,但我不确定如何使用它从 mainForm 调用函数.

欢迎提出任何想法!

解决方案

你可以把所有的命令塞进一个Dictionary;如果您可以接受所有具有相同返回类型的命令.

我已经使用了字符串并设置了一些命令.

我使用 params 关键字来避免每次调用时出现丑陋的 new object[].

您仍然需要转换参数,除非您可以将它们全部设为一种类型.(这实际上可能不是一个坏主意,因为它们都来自输入字符串..)

这是一个例子:

公共委托字符串 cmdDel(params object[] args);字典<字符串,cmdDel>cmd = 新字典<字符串,cmdDel>();

添加几个函数:

cmd.Add("clear", cmd_clear);cmd.Add("退出", cmd_exit);cmd.Add("添加", cmd_add);cmd.Add("日志", cmd_log);

有了这些身体:

公共字符串 cmd_clear(params object[] args){返回清除";}公共字符串 cmd_exit(参数对象 [] 参数){返回退出";}公共字符串 cmd_add(params object[] args){返回 ((int)args[0] + (int)args[1]).ToString();}公共字符串 cmd_log(参数对象 [] 参数){StringBuilder 日志 = new StringBuilder();foreach (args 中的对象 a) log.Append(a.ToString() + " ");返回 log.ToString();}

并测试:

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

<块引用>

清除

65

23 + 42 = 65

退出

当然,您仍然需要(至少)使用与命令一样多的行进行设置.并且还需要进行类似数量的错误检查.

但是命令处理部分可以变得非常简单.

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 something like this

public void ExecuteCommand()
    {
        string input = ReadLine(); //gets last string from input
        bool isDone = false; //need bool to check whether command was executed or no, by default false.

        Match result = Regex.Match(input, @"([^s]+)"); //to get command name
        string commandName = result.Value.ToLower();

        string value = Regex.Match(input, @"s(.*)").Value; //to get its parameter. currently everything after ' ' space.

        if (commandName == "close")
        {
            Close(); isDone = true;
        }

        //so commandline is separate window, and appendedForm is a main form. in which some functions are executed.

        if (commandName == "exit")
        {
            appendedForm.Close();
        }

        if (commandName == "spoof")
        {
            appendedForm.Fn_Spoof();
            isDone = true;
        }

        if(commandName == "spoofstop")
        {
            appendedForm.Fn_StopCapture();
            isDone = true;
        }

        if(commandName == "scan")
        {
            appendedForm.Fn_Scan(); isDone = true;
        }

        if(commandName == "clear")
        {
            output.Text = "";
            WriteLine("Console cleared. Cache is empty.");
            //data_lines.Clear();

            isDone = true;

        }
        ...
}

So that's basically it. I have a mainForm, and commandline form. string input is typed into commandline, then I check the name of command and execute some function from mainForm.

My question is, what is the best way of implementing such kind of thing? I surely can just continue writing bunch of "if"s, but something tells me that it's not the best way to make it.

I've thought of creating class "Command"

 public class Command
 {
    public string name;
    public string description;
    public bool hasParameter;

    Command()
    {

    }
 }

And storing all commands in some sort of array, but I am not sure how would I use this to call a function from mainForm.

Any ideas are welcome!

解决方案

You could stuff all commands into a Dictionary<string, someDelegate>; 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<string,  cmdDel> cmd = new Dictionary<string,  cmdDel>();

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.

这篇关于如何实现自定义命令行&amp;执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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