How to implement custom command line amp; execution(如何实现自定义命令行amp;执行)
问题描述
我正在尝试为我的应用程序构建一个自定义命令行,我有几个基本命令,我只是使用一堆if"语句来检查命令是什么.目前它看起来像这样
基本上就是这样.我有一个 mainForm 和命令行表单.字符串输入被输入到命令行,然后我检查命令的名称并从 mainForm 执行一些函数.
我的问题是,实现此类事情的最佳方式是什么?我当然可以继续写一堆如果",但有些事情告诉我,这不是最好的方法.
我想过创建命令"类
并将所有命令存储在某种数组中,但我不确定如何使用它从 mainForm 调用函数.
欢迎提出任何想法!
你可以把所有的命令塞进一个Dictionary
;如果您可以接受所有具有相同返回类型的命令.
我已经使用了字符串并设置了一些命令.
我使用 params
关键字来避免每次调用时出现丑陋的 new object[]
.
您仍然需要转换参数,除非您可以将它们全部设为一种类型.(这实际上可能不是一个坏主意,因为它们都来自输入字符串..)
这是一个例子:
添加几个函数:
有了这些身体:
并测试:
<块引用>
清除
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
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"
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:
Add a few functions:
With these bodies:
And test:
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.
这篇关于如何实现自定义命令行&执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!