使用C#CommandLine库解析命令行参数

时间:2014-11-09 23:22:47

标签: c# .net parsing command-line command-line-parsing

我正在使用nuget的CommandLine库v 1.9.71.2。遗憾的是,文档不是最新的,我不了解用于此库的高级C#语言结构,因此仅通过查看库中可用的界面,我无法提出可行的解决方案。

我的选项类看起来像这样:

class ProgramOptions
{
    [Option('l', "spotsL", Required = true, HelpText = "Lowest stock price used for calculations.")]
    public double lowestSpot { get; set; }

    [Option('h', "spotsH", Required = true, HelpText = "Highest stock price used for calculations.")]
    public double highestSpot { get; set; }

    [Option('n', "spotsN", Required = true, HelpText = "Number of (equally distributed) stock prices [spotsL,spotsH].")]
    public int spotsNumber { get; set; }

    [OptionList('m', "maturities", ',', Required = true, HelpText = "Comma separated list of options maturities (as a fraction of a year).")]
    public IList<string> maturities { get; set; } //we want double here.

    [Option('s', "strike", Required = true, HelpText = "Strike price of options.")]
    public double strikePrice { get; set; }

    [Option('v', "vol", Required = true, HelpText = "Volatility used for calculation.")]
    public double volatility { get; set; }
}

我只需要选项的长名称,但是当我将null(如文档所示)代替短名称时,我会遇到编译器错误。我还希望将成熟度作为双打列表(IList<double> maturities),但IDK如何实现这一点 - 我认为使用纯CommandLine它只适用于string列表。

第二部分是我无法解析从命令行argsProgramOptions对象的选项。正在尝试类似的事情:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(args[1]);
        ///Parse Command Line
        var options = new ProgramOptions();
        bool is_succes = Parser.Default.ParseArguments(args, options);
        Console.WriteLine("parsed? {0}",is_succes);

        Console.WriteLine(options.highestSpot);
        Console.WriteLine(options.lowestSpot);
        Console.WriteLine(options.maturities.ToString());
        Console.WriteLine(options.spotsNumber);
        Console.WriteLine(options.strikePrice);
        Console.WriteLine(options.volatility);
        Console.WriteLine("program working");
    }
}

很遗憾,它不起作用,并在False变量中提供is_succes。所有其他变量显示0 我的命令行参数是有机会让库解析类似的东西:

/spotsL 10 /spotsH 1000 /spotsN 9 /maturities 1,0.5,0.001 /strike 495 /vol 0.1

10确实由te WriteLine显示。

1 个答案:

答案 0 :(得分:2)

我对CommandLine库不是很熟悉,但是通过快速查看documentation,看起来你需要使用单个短划线(-)来表示单字符参数或者用于多字符参数的双短划线(--),即

--spotsL 10 --spotsH 1000 --spotsN 9 --maturities 1,0.5,0.001 --strike 495 --vol 0.1

编辑:如果您确实需要输入参数来使用斜杠,则需要将它们转换为破折号:

public static void FormatArguments(string[] args)
{
    for (int i = 0; i < args.Length; i++)
        if (args[i].StartsWith("/"))
            args[i] = "--" + args[i].Substring(1);
}