当控制台应用程序没有参数时,默认方法不执行

时间:2012-11-13 23:11:16

标签: c# ndesk.options

执行myExe.exe时,未执行下面的默认功能,但是当我运行myExe.exe -launch时,它正在执行。关于为什么这个应用程序默认不执行的任何想法?根据{{​​3}}这应该有效

摘自文档:

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;
    }
}

1 个答案:

答案 0 :(得分: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");
    }
}