【问题标题】:How to use ndesk options to add an option that takes three arguments?如何使用 ndesk 选项添加一个需要三个参数的选项?
【发布时间】:2018-11-08 19:45:59
【问题描述】:

我想在我的命令行选项集中添加一个类似-D=Id1:Id2:Id3 的选项。 我怎样才能做到这一点 ?此选项必须是强制性的。

我尝试过这样做:

var optSet = new OptionSet() 
{
    { "D:", "Device to communicate with.",
        (int id1, int id2, int id3) => {
            if (id1 == null)
                throw new OptionException ("Missing Id1 for option -D.", "-D");
            if(id2 == null)
                throw new OptionException ("Missing Id2 for option -D.",  "-D");
            if(id3 == null)
                throw new OptionException ("Missing Id3 for option -D.",  "-D"); 
} },

但我收到错误消息说该操作只需要 2 个参数。

【问题讨论】:

  • ndesk.options 似乎不支持这一点。你可以做的是使用一个只接受1个字符串的函数并自己解析它(由':'分割然后将每个子字符串解析为一个int)。 int 也不能​​为空。
  • 是的,这就是我最终所做的。无论如何谢谢:)

标签: c# command-line-arguments ndesk.options


【解决方案1】:

改用类似 CSV/SSV 的语法,例如-D=Id1,Id2,Id3-D=Id1;Id2;Id 等。然后使用 NDesk.Options 解析为单个组合结果 Id1,Id2,Id3 然后使用 .Split(',') 验证长度或计数为 3 或打印使用消息。

修改 NDesk.Options 应该很容易——它只是一个文件——通过在内部拆分数组并返回它来为你处理这个问题。

我也不得不这样做,因为我认为非法的空选项,例如- 如果我记得,因为我不喜欢默认行为。它现在已成为我首选的 C# 命令行选项处理程序以及以下 C#(和 Python)中的 {--/}key=value 解析器,带或不带前导选项字符:

public static Dictionary<string, string> KVs2Dict(IEnumerable<string> args, Dictionary<string, string> defaults = null)
{
    Dictionary<string, string> d = defaults ?? new Dictionary<string, string>();
    foreach (string arg in args)
    {
        string s = arg.TrimStart(new[] { '-', '/' });
        string[] sa = s.Split(new[] { '=' }, 1);
        string k = sa[0].Trim('"');
        if (s.Contains('='))
        {
            string v = sa[1].Trim('"');
            d[k] = v;
        }
        else
            d[k] = null;
    }
    return d;
}

保持简单:有了这个,您甚至不需要 NDesk.Options 来实现简单的应用程序。

添加多个值有多容易?简单:只需添加另一个条件并返回 Dictionary

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多