简体   繁体   English

NDesk.Options - 检测无效参数

[英]NDesk.Options - detect invalid arguments

I am using NDesk.Options to parse command line arguments for a C# command line program. 我正在使用NDesk.Options来解析C#命令行程序的命令行参数。 It is working fine, except I want my program to exit unsuccessfully, and show the help output, if the user includes arguments that I did not expect. 它工作正常,除了我希望我的程序退出失败,并显示帮助输出,如果用户包含我没想到的参数。

I am parsing options thusly: 我正在解析选项:

var options = new OptionSet {
    { "r|reset",  "do a reset", r => _reset = r != null },
    { "f|filter=",  "add a filter", f => _filter = f },
    { "h|?|help",  "show this message and exit",  v => _showHelp = v != null },
};

try
{
    options.Parse(args);
}
catch (OptionException)
{
    _showHelp = true;
    return false;
}
return true;

With this code, if I use an argument improperly, such as specifying --filter without =myfilter after it then NDesk.Options will throw an OptionException and everything will be fine. 使用此代码,如果我使用不正确的参数,例如在其后指定--filter without =myfilter myfilter,则NDesk.Options将抛出OptionException,一切都会好的。 However, I also expected an OptionException to be thrown if I pass in an argument that doesn't match my list, such as --someOtherArg . 但是,如果我传入一个与我的列表不匹配的参数,我也期望抛出一个OptionException,例如--someOtherArg But this does not happen. 但这不会发生。 The parser just ignores that and keeps on trucking. 解析器只是忽略了它并继续卡车运输。

Is there a way to detect unexpected args with NDesk.Options? 有没有办法用NDesk.Options检测意外的args?

The OptionSet.Parse method returns the unrecognized options in a List<string> . OptionSet.Parse方法返回List<string>无法识别的选项。 You can use that to report unknown options. 您可以使用它来报告未知选项。

try
{
    var unrecognized = options.Parse(args);
    if (unrecognized.Any())
    {
        foreach (var item in unrecognized) 
            Console.WriteLine("unrecognized option: {0}", item);
        _showHelp = true;
        return false;
    }
}
catch (OptionException)
{
    _showHelp = true;
    return false;
}
return true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM