如何使用C#中的NDesk选项解析一个简单的项目列表

时间:2013-07-02 09:27:10

标签: c# ndesk.options

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

实施例:  prog --items = item1 item2 item3  (我想在代码中使用List项目)

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

prog --items =“c:\ a \ b \ c.txt”“c:\ prog files \ d.txt”  prog --dirs =“c:\ prog files \”“d:\ x \ y \ ddname中的空格”

2 个答案:

答案 0 :(得分:5)

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

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);

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

答案 1 :(得分:4)

您可以使用&#34;&lt;&gt;&#34;输入表示没有标志与输入相关联。由于选项是从左到右阅读的,因此您可以设置“当前参数”&#39;遇到起始标志时标记,并假设没有标志的任何后续输入都是列表的一部分。下面是一个示例,我们可以将List指定为输入文件,并将Dictionary(参数)指定为键值对列表。当然也有其他变化。

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);