0

下面的默认功能在我执行时没有被执行myExe.exe,但是在我运行时它正在执行myExe.exe -launch。关于为什么此应用程序默认不执行的任何想法?根据文档,这应该可以

文档摘录:

As a fallback, a default handler may be registered which will handle all arguments which are not handled by any of the above matching algorithms. The default handler is designated by the name <> (which may be an alias for another named NDesk.Options.Option).

我的代码:

public static void Main (string[] args)
{
    bool showHelp = false;
    var options = new OptionSet() {
        {
            "h", "Show help",
            v => showHelp = true
        }, {
            "config", "Reconfigure the launcher with different settings",
            v => PromptConfig()
        }, {
            "v", "Show current version",
            v => ShowVersion()
        }, {
            "launch",
            v => LaunchApplication()
        }, {
            "<>", //default
            v => LaunchApplication()
        }
    };

    //handle arguments
    List<string> extra;
    try {
        extra = options.Parse (args);
    }
    catch (OptionException e) {
        Console.Write("MyApp:");
        Console.WriteLine(e.Message);
        Console.WriteLine("Try `MyApp--help' for more information");
        return;
    }

    if (showHelp) {
        ShowHelp(options);
        return;
    }
}
4

1 回答 1

1

默认处理程序旨在处理您没有为其提供特定处理程序的任何参数。

在您的情况下,运行MyExe.exe不应调用默认处理程序,因为没有要处理的参数。如果您运行命令行,MyExe.exe -someUnknownArgument 那么默认处理程序应该启动。

无论如何,我相信该Parse方法的目的是帮助您解析命令行并初始化您自己的表示参数的模型,然后对其进行操作。

因此,例如,您的代码可能如下所示:

public enum Action
{
    ShowHelp,
    ShowVersion,
    PromptConfig,
    LaunchApplication
}

public static void Main (string[] args)
{
    var action = Action.LaunchApplication;

    var options = new OptionSet() {
        {
            "h", "Show help",
            v => action = Action.ShowHelp
        },
        {
            "config", "Reconfigure the launcher with different settings",
            v => action = Action.PromptConfig
        },
        {
            "v", "Show current version",
            v => action = Action.ShowVersion
        }, 
        {
            "launch",
            v => action = Action.LaunchApplication
        }
    }

    try 
    {
        // parse arguments
        var extra = options.Parse(args);

        // act
        switch (action)
        {
            // ... cases here to do the actual work ...
        }
    }
    catch (OptionException e) 
    {
        Console.WriteLine("MyApp: {0}", e.Message);
        Console.WriteLine("Try `MyApp --help' for more information");
    }
}
于 2012-11-13T23:21:55.807 回答