[英]Mono.Options: Check if an invalid option is given
I've defined 我已经定义
var p = new OptionSet () {
// various options defined
};
Then I 然后我
p.Parse(args)
If I call my program with 如果我用
myprogram --thisOptionIsNotDefined
I would like to display a help message, and NOT continue. 我想显示帮助消息,而不继续。 But Parse() doesn't throw an OptionException when it encounters an invalid option.
但是,当Parse()遇到无效选项时,它不会引发OptionException。 What do I do?
我该怎么办?
You can interrogate the return of OptionSet.Parse()
to find any invalid parameters. 您可以查询
OptionSet.Parse()
的返回值以查找任何无效参数。
From the NDesk OptionSet documentation : 从NDesk OptionSet 文档中 :
OptionSet.Parse(IEnumerable), returns a List of all arguments which were not matched by a registered NDesk.Options.Option.
OptionSet.Parse(IEnumerable),返回所有与注册的NDesk.Options.Option不匹配的参数的列表。
OptionSet.Parse()
returns any unprocessed arguments. OptionSet.Parse()
返回所有未处理的参数。 However, note that this may also includes any actual (non-option) argument of your program, eg input files. 但是,请注意,这可能还包括程序的任何实际(非选项)参数,例如输入文件。 In that case you can't just check that nothing is returned.
在这种情况下,您不能只检查没有返回任何内容。
Eg parsing the below args
will return ["input.txt", "--thisOptionIsNotDefined"]
. 例如,解析以下
args
将返回["input.txt", "--thisOptionIsNotDefined"]
。
myprogram input.txt --thisOptionIsNotDefined
To solve this particular problem, I wrote an extension method p.ParseStrict(args)
. 为了解决这个特定问题,我编写了一个扩展方法
p.ParseStrict(args)
。 It simply checks that no options remain unprocessed after parsing (taking --
into account). 它只是将检查解析(服用后没有选项还未经处理
--
进入帐户)。
public static class MonoOptionsExtensions
{
public static List<string> ParseStrict(this OptionSet source, IEnumerable<string> arguments)
{
var args = arguments.ToArray();
var beforeDoubleDash = args.TakeWhile(x => x != "--");
var unprocessed = source.Parse(beforeDoubleDash);
var firstUnprocessedOpt = unprocessed.Find(x => x.Length > 0 && (x[0] == '-' || x[0] == '/'));
if (firstUnprocessedOpt != null)
throw new OptionException("Unregistered option '" + firstUnprocessedOpt + "' encountered.", firstUnprocessedOpt);
return unprocessed.Concat(args.SkipWhile(x => x != "--").Skip(1)).ToList();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.