解析和执行命令

本文关键字:命令 执行 | 更新日期: 2023-09-27 18:27:49

我正在为我的项目制作一个调试控制台,从TextBox等中获取输入

然而,我想知道,除了一个巨大的切换声明之外,是否还有其他选择:

switch(command.ToLower) {
case "example":
    // do things...
    break;
case "example2":
    // do things...
    break;
}

因为我觉得有一个更优雅的解决方案可用,但我的技能无法访问它。

编辑:由于@OwlSolo的惊人贡献,我现在的代码可以工作了,我在下面发布了我提交的代码的修改版本,它对我来说是有效的。谢谢@OwlSolo,你是一个打字的传奇!

class parseCommand
{
    public static commandBase commandInstance { get; set; }
    public static void parse(string command)
    {
        string[] tokens = command.Split(' '); // tokens[0] is the original command
        object[] parameters = tokens.Skip(1).ToArray();
        List<Type> cmdTypes = System.Reflection.Assembly
            .GetExecutingAssembly()
            .GetTypes()
            .Where(t => typeof(commandBase).IsAssignableFrom(t))
            .ToList();
        foreach(Type derivedType in cmdTypes)
        {
            if (derivedType.Name.ToLower() == tokens[0].ToLower())
            {
                commandInstance = (commandBase)Activator.CreateInstance(derivedType);
                commandInstance.parameters = parameters;
                commandInstance.Execute();
                break;
            }
        }
    }
}

解析和执行命令

解析某种语言本身基本上是一门完整的学科,因此这个问题相当宽泛。语言lexer和解析器通常创建命令的树结构,这些命令在保留的关键字和参数中分离。保留的关键字包含例如命令。(如类C语言中的switchifgoto等)问题是,这些命令是以一种相互独立的方式进行理想选择的。这意味着关键词本身会引发一种截然不同的处理方式。微调是通过参数来完成的。

如果这适用于您的命令,那么您就没有太多的选择来提供处理每个命令的独立方法。例如,JavaCC(JavaCompiler Compiler)生成了一个代码库,该代码库具有相当大的开关用例,可以生成指令树。然后由用户来评估所提供的指令树,这通常是通过处理关键字的单个对象来完成的,因此可能存在一个类IfStatement,它包含许多子指令并处理其执行。

无论您在这里需要什么,真正的工作将是如何处理执行,而不是如何区分哪个命令调用哪个行为。

你可能想要的结构可能看起来像这样:

abstract class BinaryCommand
{
    MyBaseCommand child1;
    MyBaseCommand child2;
    abstract object Execute();
}
class ExampleCommand1 : BinaryCommand
{
    override object Execute()
    {
         //DoStuff1...
    }
}
class ExampleCommand2 : BinaryCommand
{
    override object Execute()
    {
         //Do Somethign else
    }
}

至于区分你的关键词,有很多方法:

  • 一个大的switch语句。

  • 持有一个Dictionary<string, Type>,从中可以查找处理命令的Type。例如:"Example1 abcde 12345"将查找"Example 1",在字典中创建该类型的实例,并使用参数"abcde"answers"12345"进行填充。

  • 一个相当大胆的方法是通过代码来反映一个可以处理该命令的类
    您将有一个类似IBaseCommand的接口,所有的命令类都是从该接口派生的。

// Get all the types that derive from your base type
List<Type> commandTypes = Assembly
    .GetExecutingAssembly()
    .GetTypes()
    .Where(t => typeof(IBaseCommand).IsAssignableFrom(t));
foreach (Type derivedType in commandTypes)
{
    // Distinguishing by class name is probably not the best solution here, but just to give you the general idea
    if (derivedType.Name == command.ToLower) 
    {
        // Create an instance of the command type
        IBaseCommand myCommandInstance = Activator.CreateInstance(derivedType);
        //Call the execute method, that knows what to do
        myCommandInstance.Execute();
    }
}

编辑:根据评论中提供的信息,您可以执行类似的操作

Interface ICommandBase
{
    object[] parameters {get; set;}
    void Execute();    
}
abstract class InternalCommand : ICommandBase
{
    //Some methods that are common to all your intzernal commands
}
class SetColorCommand : InternalCommand //Or it might derive from ICommandBase directly if you dont need to categorize it
{
     object[] parameters {get; set;}
     void Execute()
     {
         switch (parameters[0])
         {
              case "background":
                  //Set the background color to parameters[1]
              break;
              case "foreground":
                    //...
              break;
         }
     }
}
class SqlCommand : ICommandBase
// Or it might derive from ICommandBase directly if you don't need to categorize it
{
     object[] parameters {get; set;}
     void Execute()
     { 
          //Parameters[0] would be the sql string...
     } 
}

然后通过解析整个过程

// Assuming you're getting one command per line and one line is fed to this function
public void ParseCommands(string command)
{
    string[] tokens = command.Split(" ");
    // tokens[0] is the command name
    object[] parameters = (object[])tokens.Skip(1);//Take everything but the first element (you need to include LINQ for this)
    // Get all the types that derive from your base type
    List<Type> commandTypes = Assembly
        .GetExecutingAssembly()
        .GetTypes()
        .Where(t => typeof(IBaseCommand).IsAssignableFrom(t));
    foreach (Type derivedType in commandTypes)
    {
        if (derivedType.Name.ToLower == tokens[0].ToLower) 
        /* Here the class name needs to match the commandname; this yould also be a
           static property "Name" that is extracted via reflection from the classes for 
           instance, or you put all your commands in a Dictionary<String, Type> and lookup 
           tokens[0] in the Dictionary */
        {
            // Create an instance of the command type
            IBaseCommand myCommandInstance = Activator.CreateInstance(derivedType);
            myCommandInstance.parameters = parameters;
            myCommandInstance.Execute(); // Call the execute method, that knows what to do
                 break;
        }
    }   
}

您的目标是拥有尽可能少的命令,并通过参数尽可能多地执行操作。

不是真的。。。我唯一要做的就是将不同类型的命令拆分为不同的方法,使其更加精简/优雅,并使用泛型集合来存储应用于每种类型的命令。

示例:

List<string> MoveCommands = new List<string>(){"Move", "Copy", "Merge"};
List<string> Actions = new List<string>() {"Add", "Edit", "Delete"};
//.......
if(MoveCommands.contains(inputtext))
    ExecuteMoveCommand();
else if (Actions.contains(inputtext))
    ExecuteActionCommand();

诸如此类的东西。。。你所走的路线只会让优雅和代码整洁发挥作用。

您可以执行以下操作:

var lookup = new Dictionary<string, YourParamType> ()  
{
  { "example", a  },
  { "example2", b },
   ....
};
YourParamType paraType;
if (lookup.TryGetValue(command.ToLower(), out para))   // TryGetValue, on popular      request
{       
   //your code
}

一年前我解决了同样的问题。因此,我将以我的代码为例解释它是如何工作的,这样您就知道如何设计命令行解析器以及如何解决您的问题。

正如OwlSolo已经说过的,你需要一个基类或接口,它将能够接受参数并执行一些逻辑。

在Cmd.Net的情况下,它是Command类:

public abstract class Command
{
    protected Command(string name);
    public string Name { get; }
    public abstract void Execute(ArgumentEnumerator args);
}

该班有两名成员:

  1. 为命令提供名称的属性Name
  2. 方法Execute接受参数并执行业务逻辑

ArgumentEnumerator像上面在OwlSolo的代码中提到的string.Split方法一样分割所提供的string,但方式更复杂。它生成参数名称和值的键值对。

举个例子,您有一个字符串,它看起来像这样:

"/namedArg:value1 value2"

将被解析为两对。第一对是名为"namedArg"、值为"value1"的命名参数。第二个是值为"value2"的未命名参数(名称等于string.Empty)。

命名参数的目的是允许重新排列它们,并使其中一些参数成为可选参数。这将提高可用性。

现在,我们想要一个命令集合,您可以更快地从中获取其中一个命令的名称。Dictionary<string, Command>是最好的选择,但让我们进一步了解并制作一个将控制权转移到子命令的命令。因此,我们将能够像netsh中那样构建命令类别/层次结构。

public sealed class CommandContext : Command
{
    public CommandContext(string name);
    public CommandCollection Commands { get; }
    public override void Execute(ArgumentEnumerator args);
}
public sealed class CommandCollection : KeyedCollection<string, Command>
{
    public CommandCollection() 
        : base(StringComparer.OrdinalIgnoreCase) 
    { 
    } 
    protected override string GetKeyForItem(Command item)
    { 
        return item.Name;
    }
    public bool TryGetCommand(string name, out Command command)
    { 
        return Dictionary.TryGetValue(name, out command);
    }
}

如果未命名,则重写的Execute方法将采用第一个参数,并使用TryGetCommand方法搜索命令。当它找到该命令时,它将使用除第一个参数之外的所有参数执行该命令。如果没有找到命令,或者第一个参数有名称,那么我们应该显示一个错误。

注意由于我们使用StringComparer.OrdinalIgnoreCase,因此不必担心传递的name中的字符大小写。

现在是时候考虑自动参数解析和转换了。为了实现这一点,我们可以使用反射和TypeConverters.

public sealed class DelegateCommand : Command
{
    public DelegateCommand(Delegate method);
    public Delegate Method { get; }
    public override void Execute(ArgumentEnumerator args);
}

DelegateCommand的构造函数中,您应该收集有关method的参数(名称、默认值、类型转换器等)的信息,然后在Execute方法中使用这些信息来强制转换并为method提供参数。

我省略了实现细节,因为它很复杂,但您可以在DelegateCommand.cs和Argument.cs.中了解到这一点

最后,您将能够在不进行任何解析的情况下执行方法

CommandContext root = new CommandContext(
    "root",
    new Command("multiply", new Action<int, int>(Multiplication)),
    new CommandContext(
        "somecontext",
        // ...
        )
    );
ArgumentEnumerator args = new ("add /x:6 /y:7");
root.Execute(args);
public static void Multiplication([Argument("x")] int x, [Argument("y")] int y)
{
    // No parsing, only logic
    int result = x * y;
}