【问题标题】:How to parse a simple list of items with NDesk Options in C#如何在 C# 中使用 NDesk 选项解析一个简单的项目列表
【发布时间】:2013-06-29 14:34:56
【问题描述】:

我是 NDesk.Options 库的新手。无法找出解析简单项目列表的最简单方法。

示例: 编 --items=item1 item2 item3 (我想在代码中使用List items)

它应该支持引用以及我想将项目列表用作文件或目录名称的列表。

prog --items="c:\a\b\c.txt" "c:\prog 文件\d.txt" prog --dirs="c:\prog 文件\" "d:\x\y\目录名中的空间"

【问题讨论】:

    标签: c# ndesk.options


    【解决方案1】:

    您可以使用“”输入,它表示没有与输入关联的标志。由于选项是从左到右读取的,因此您可以在遇到起始标志时设置“currentParameter”标志,并假设任何没有标志的后续输入都是列表的一部分。这是一个示例,我们可以将 List 指定为输入文件,并将 Dictionary (Parameters) 指定为键值对列表。当然也可以使用其他变体。

    OptionSet options = new OptionSet()
            {
                {"f|file", "a list of files" , v => {
                    currentParameter = "f";
                }},
                {"p", @"Parameter values to use for variable resolution in the xml - use the form 'Name=Value'.  a ':' or ';' may be used in place of the equals sign", v => {
                    currentParameter = "p";
                }},
                { "<>", v => {
                    switch(currentParameter) {
                        case "p":
                            string[] items = v.Split(new[]{'=', ':', ';'}, 2);
                            Parameters.Add(items[0], items[1]);
                            break;
                        case "f":
                            Files.Add(Path.Combine(Environment.CurrentDirectory, v));
                            break;
                    }
                }}
            };
    options.Parse(args);
    

    【讨论】:

      【解决方案2】:

      接受单个参数的值列表的另一种方法是多次接受相同的参数。例如,

      prog --file="c:\a\b\c.txt" --file="c:\prog files\d.txt"

      在这种情况下,您的代码将如下所示。

      List<string> fileList = new List<string>();
      
      OptionSet options = new OptionSet
      {
          { "f|file", "File name. Repeat argument for each file.", v =>
              {
                  fileList.Add(v);
              }
          }
      };
      
      options.Parse(args);
      

      恕我直言,此代码更易于阅读和维护。

      【讨论】:

        猜你喜欢
        • 2018-11-08
        • 2011-10-29
        • 2014-11-23
        • 2015-12-26
        • 2011-11-12
        • 2013-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多