还有一个更基本的问题:命令行上的 key=value 集的数量是否有限制?
如果 key=value 集的数量是可变的,那么您希望使用<> 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]);
} },
};
这将拆分 /p1 之后的所有 key=value 选项并将它们添加到 p1 字典中:
p.Parse (new[]{"/p1", "key1=value1", "key2=value2", "/p2"});
// `p1` now contains { { "key1", "value1" }, {"key2", "value2" } }
出于显而易见的原因,我认为上述方法是合理的。
但是,如果总是有 3 个集合(因此需要 6 个值),您可以改为创建一个需要 6 个值的 Option 子类:
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)));
}
}
然后您可以将此 ActionOption 提供给OptionSet.Add(Option):
var p = new OptionSet {
new ActionOption<string, string, string, string, string, string> (
"p1", null, (a, b, c, d, e, f) => {...}),
};