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. What do I do?
You can interrogate the return of OptionSet.Parse()
to find any invalid parameters.
From the NDesk OptionSet documentation :
OptionSet.Parse(IEnumerable), returns a List of all arguments which were not matched by a registered NDesk.Options.Option.
OptionSet.Parse()
returns any unprocessed arguments. 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"]
.
myprogram input.txt --thisOptionIsNotDefined
To solve this particular problem, I wrote an extension method 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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.