c# - 实现命令行解释器

标签 c# command-line

在终端或cmd中,您可以编写命令,其中有一个主命令,然后是子命令,或者参数之类的东西......就像这样:

cd Desktop\Folder
lst
Format E: /fs:FAT32

我想创建一个 C# 控制台应用程序,它可以执行这样的预定义命令,但它也可以拆分主命令和子命令,其中有些命令是可选的,有些不是。我尝试将所有内容作为字符串,然后将其拆分为数组并创建 if(s)switchcase ,但它看起来真的很糟糕而且很难管理。我确信在操作系统的终端或 cmd 中它是以另一种方式构建的。您能帮我了解这样一个应用程序的基本结构吗?

最佳答案

在这里,看看这个概念。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharpConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to SharpConsole. Type in a command.");

            while (true)
            {
                Console.Write("$ ");
                string command = Console.ReadLine();

                string command_main = command.Split(new char[] { ' ' }).First();
                string[] arguments = command.Split(new char[] { ' ' }).Skip(1).ToArray();
                if (lCommands.ContainsKey(command_main))
                {
                    Action<string[]> function_to_execute = null;
                    lCommands.TryGetValue(command_main, out function_to_execute);
                    function_to_execute(arguments);
                }
                else
                    Console.WriteLine("Command '" + command_main + "' not found");
            }
        }

        private static Dictionary<string, Action<string[]>> lCommands = 
            new Dictionary<string, Action<string[]>>()
            {
                { "help", HelpFunc },
                { "cp" , CopyFunc }
            };

        private static void CopyFunc(string[] obj)
        {
            if (obj.Length != 2) return;
            Console.WriteLine("Copying " + obj[0] + " to " + obj[1]);
        }

        public static void HelpFunc(string[] args)
        {
            Console.WriteLine("===== SOME MEANINGFULL HELP ==== ");
        }
    }
}

基本思想是概括命令的思想。我们有一个Dictionary ,其中键是一个字符串(命令的名称),从字典中获取的值是 Action<string[]> 类型的函数 。具有签名 void Function(string[]) 的任何函数可以用作这种类型。然后,您可以使用一堆命令设置此字典并将它们路由到您想要的功能。这些函数中的每一个都将接收一组可选参数。所以在这里,命令“help”将被路由到HelpFunc() 。和“cp”命令,例如将收到一个文件名数组。命令的解析始终是相同的。我们读一行,将其分成一个空格。第一个字符串是程序的名称 command_main这里。如果跳过第一个字符串,您将获得您输入的所有其他子命令或开关的枚举。然后,将在字典中查找以查看是否存在这样的命令。如果是,我们获取该函数并使用参数执行它。如果没有,您应该显示“未找到命令”或其他内容。总而言之,这个练习可以最小化为在可能的命令字符串字典中查找函数,然后执行它。所以可能的输出是

Welcome to SharpConsole. Type in a command. 
$ help
===== SOME MEANINGFULL HELP ==== 
$ cp file1 otherfile2 
Copying file1 to otherfile2 
$ python --version
Command 'python' not found
$ ...

关于c# - 实现命令行解释器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468268/

相关文章:

command-line - 如何使用 vbc 命令行编译器(无 IDE)像 shdocvw 一样引用 COM 库?

linux - 从批处理中终止交互式程序

java - 将命令行参数传递给 javaws (Java WebStart) 可执行文件

c# - 如何从相对路径加载c#中的json文件?

C# 半透明 'LightBox' 控件调用Parent的paint方法

c# - 查找 C# 列表中是否存在值的最有效方法

linux - 仅适用于 CLI 的 IDE Debian Linux 发行版

c# - 在什么时候我需要将查询工作卸载到数据库?

c# - 在 C# 中制作备份实用程序

mysql - 如何从命令行连接到 MySQL