c# - 将命令映射到方法

标签 c#

我有一个命令行应用程序,我使用字典将命令映射到方法,从单字母命令到方法名称(作为字符串)。我可以使用此方法来调用它,也可以告诉用户可用命令的列表,如下所示:

private static readonly Dictionary<string, string> commands =
    new Dictionary<string, string>
    {
        {"u", "DestroyUniverse"},
        {"g", "DestroyGalaxy"},
        {"p", "DestroyPlanet"},
        {"t", "TimeTravel"}
    };

public void DestroyUniverse(Stack<string> argStack)
{
     // destroy the universe according to the options in argStack
     // ...
}

public void DestroyGalaxy(Stack<string> argStack)
{
     // destroy the galaxy according to the options in argStack
     // ...
}

// ... other command methods

public void Run(Stack<string> argStack)
{
    var cmd = argStack.Next();
    string methodName;

    // if no command given, or command is not found, tell
    // user the list of available commands

    if (cmd == null || !commands.TryGetValue(cmd, out methodName))
    {
        Console.WriteLine("Available Commands:{0}{1}", 
            Environment.NewLine, 
            string.Join(Environment.NewLine,
            commands.OrderBy(kv => kv.Key)
                    .Select(kv => string.Format("{0} - {1}", kv.Key, kv.Value))));

        Environment.ExitCode = 1;
        return;
    }

    // command is valid, call the method

    GetType().GetMethod(methodName).Invoke(this, new object[] {argStack});
}

这工作正常,但我不喜欢使用字符串作为字典中的值。因此,没有编译器支持来确保每个字符串都有一个方法。我宁愿以某种方式使用“方法”,但仍然可以访问方法的名称,用于列出命令的部分。有类似的东西吗?

最佳答案

为什么这不起作用?

class Program
{
    static void Main(string[] args)
    {
        var p = new Program();
        p.Run(new Stack<string>(args.Reverse()));
        Console.ReadKey();
    }

    private readonly Dictionary<string, Action<Stack<string>>> commands;

    public Program() {
        commands =
            new Dictionary<string, Action<Stack<string>>>
            {
                {"u", DestroyUniverse },
                {"g", DestroyGalaxy },
                {"p", DestroyPlanet },
                {"t", TimeTravel }       
            };
     }

    public void DestroyUniverse(Stack<string> argStack)
    {
        // destroy the universe according to the options in argStack
        // ...
    }

    public void DestroyGalaxy(Stack<string> argStack)
    {
        // destroy the galaxy according to the options in argStack
        // ...
    }

    private string Next(Stack<string argStack)
    {
        // wish this was a method of Stack<T>
        return argStack.Any() ? argStack.Pop() : null;
    }

    public void Run(Stack<string> argStack)
    {
        var cmd = Next(argStack);

        Action<Stack<string>> action = null;

        // if no command given, or command is not found, tell
        // user the list of available commands
        if (cmd == null || !commands.TryGetValue(cmd, out action))
        {
            Console.WriteLine("Available Commands:{0}{1}",
                Environment.NewLine,
                string.Join(Environment.NewLine,
                    commands.OrderBy(kv => kv.Key)
                        .Select(kv => string.Format("{0} - {1}",
                             kv.Key, kv.Value.Method.Name))));
            Environment.ExitCode = 1;
            return;
        }

        // command is valid, call the method
        action(argStack);
    }
}

关于c# - 将命令映射到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33902685/

相关文章:

c# - 以新格式打开图像C#

c# - .GetProperties() 的大 O

c# - 在 Xamarin 中使用 Azure AD 的跨应用 SSO

c# - 如何将 C 指针编码到 C# 结构数组

c# - Activator.CreateInstance(t, 42, args) 找不到构造函数

c# - Orleans 7.0 序列化程序无法与源自 Nuget 包的 POCO 一起使用

c# - 如何在词典集中查找项目?

c# - 在 Unity C# WWW 中显示进度条

c# - 如何在wpf中自动调整富文本框的大小?

c# - CodeMaid 工具栏下拉菜单未出现在 Visual Studio 2017 中