NDesk.Options/Mono.Options: Parameter with multiple key/value pairs
I need to parse the following command line syntax:
MyApplication.exe /p1 key1=value1 key2=value2 key3=value3 /p2
key1, key2 & key3 belong to parameter p1.
I'开发者_如何学运维ve found Example #3 in the documentation, which shows a way to parse for a single key/value pair.
Is parsing for multiple key/value pairs for a single parameter possible with NDesk.Options
There's a more fundamental question in play: is there a limit to the number of key=value sets on the command line?
If the number of key=value sets is variable, then you want to use argument runs as permitted by the <>
default handler:
Dictionary<string, string> cur = null;
Dictionary<string, string> p1 = new Dictionary<string, string>();
Dictionary<string, string> p2 = new Dictionary<string, string>();
var p = new OptionSet () {
{ "p1", v => { cur = p1; } },
{ "p2", v => { cur = p2; } },
{ "<>", v => {
string[] values = v.Split (new[]{'=', ':'}, 2);
cur.Add (values [0], values [1]);
} },
};
This will split all key=value options after /p1
and add them to the p1
dictionary:
p.Parse (new[]{"/p1", "key1=value1", "key2=value2", "/p2"});
// `p1` now contains { { "key1", "value1" }, {"key2", "value2" } }
For obvious reasons, I'd consider the above to be the reasonable way to go.
However, if there will always be 3 sets (and thus 6 required values), you could instead create an Option subclass which requires 6 values:
class ActionOption<T1, T2, T3, T4, T5, T6> : Option {
Action<T1, T2, T3, T4, T5, T6> action;
public ActionOption (string prototype, string description,
Action<T1, T2, T3, T4, T5, T6> action)
: base (prototype, description, 6)
{
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<T1>(c.OptionValues [0], c)),
Parse<T2>(c.OptionValues [1], c)),
Parse<T3>(c.OptionValues [2], c)),
Parse<T4>(c.OptionValues [3], c)),
Parse<T5>(c.OptionValues [4], c)),
Parse<T6>(c.OptionValues [5], c)));
}
}
You can then provide this ActionOption to OptionSet.Add(Option)
:
var p = new OptionSet {
new ActionOption<string, string, string, string, string, string> (
"p1", null, (a, b, c, d, e, f) => {...}),
};
NDesk.Options has special syntax to suport exactly this:
var pars = new Hashtable();
var opts = new NDesk.Options.OptionSet{
{"p={:}{/}", (n,v) => pars.Add(n, v)}
};
Now you can run your program with command line like this:
-p=key1:value1 -p=key2/value2
Notice, that you can set pairs delimiter in options configuration. In this example it is [:/]
精彩评论