0

我正在使用 C# CommandLineParser 来处理我的命令行参数。

https://github.com/commandlineparser/commandline

我在命令行上允许的唯一选项是:

myprogram.exe -a 4 -b -c value

如果我不小心忘记了可选选项(参数)上的破折号,例如:

myprogram.exe -a b -c

该程序仍然运行并且不会抱怨“b”。如果指定了这样的预期参数,我如何报告错误?我试过使用:

var parser = new CommandLine.Parser(s =>
{
    s.IgnoreUnknownArguments = false;
});

但这似乎没有标记任何错误。想法?

4

2 回答 2

0

我不熟悉 C# CommandLinePArser 类,但是从它的文档看它与Apache Commons CLI非常相似,所以我将根据相似性提供一个建议(这不应该被视为一个完整的答案)。在您的情况下,程序不会抱怨“b”,因为它被视为选项“a”的参数。唯一的方法是在程序的解析阶段处理它。一种方法是查询命令行是否存在选项及其值,然后检查该值是否在该选项的允许空间内,请参阅CLI 命令行查询。希望能帮助到你。

于 2019-06-22T05:29:34.823 回答
0

FluentArgs(参见:https ://github.com/kutoga/FluentArgs )有一个选项来控制这种行为。它使用预定义的错误消息,但可以自定义(在 Github 页面上搜索RegisterParsingErrorPrinter )。您的代码看起来像(假设所有参数都是可选的):

using FluentArgs;
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            FluentArgsBuilder.New()
                .DisallowUnusedArguments()
                .Parameter("-a").IsOptional()
                .Parameter("-b").IsOptional()
                .Parameter("-c").IsOptional()
                .Call(c => b => a =>
                {
                    Console.WriteLine($"a={a ?? "null"}");
                    Console.WriteLine($"b={b ?? "null"}");
                    Console.WriteLine($"c={c ?? "null"}");
                })
                .Parse(args);
        }
    }
}

我假设a,bcare string-arguments。如果它们是标志,则可以这样做:

using FluentArgs;
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            args = new[] { "-a", "hey", "du" };
            FluentArgsBuilder.New()
                .DisallowUnusedArguments()
                .Flag("-a")
                .Flag("-b")
                .Flag("-c")
                .Call(c => b => a =>
                {
                    Console.WriteLine($"a={a}");
                    Console.WriteLine($"b={b}");
                    Console.WriteLine($"c={c}");
                })
                .Parse(args);
        }
    }
}
于 2019-10-19T08:38:15.240 回答