0

我已经开始使用这个https://github.com/commandlineparser/commandline 将解析的输入参数传递给我的应用程序。

我的问题是不需要传递的输入参数,这意味着您可以在不指定它们的情况下启动应用程序。

到目前为止,我已经定义了我的命令行选项

   public class CommandLineOptions
    {
        [Option(longName: "client-id", Required = false, HelpText = "Id of the client")]
        public string ClientId { get; set; }

        [Option(longName: "pw", Required = false, HelpText = "pw.")]
        public string Password{ get; set; }
    }

我主要是这样解析它们的

Access access= Parser.Default.ParseArguments<CommandLineOptions>(args)
                .MapResult(parsedFunc: (CommandLineOptions opts) => new Access(opts.ClientId, opts.Password),
                           notParsedFunc: (IEnumerable<Error> a) => new Access());

我想使用parsedfunc:它以防它被指定,notParsedFunc: 以防它没有被指定。

但这总是会触发parsedFuncand 因为两个参数的值都是null,所以我的内部方法失败了?

我也尝试将选项更改为不需要,然后在控制台窗口中引发错误,这些参数尚未指定,但会触发正确的方法。

4

1 回答 1

0

文档中:

如果解析成功,您将获得派生的 Parsed 类型,该类型通过其 Value 属性公开 T 的实例。

如果解析失败,您将获得一个派生的 NotParsed 类型,错误序列中存在错误。

NotParsed解析失败时调用,但在您的情况下解析成功,因为允许空密码。

您需要使用Parsed并手动检查参数是否存在:

Access access = Parser.Default.ParseArguments<CommandLineOptions>(args)
    .MapResult(
        opts => opts.Password == null ? new Access() : new Access(opts.ClientId, opts.Password),
        _ => null
    );
if(access == null)
{
    // Fail to create access
    // Close withe exit code 1
    Environment.Exit(1);
}
于 2021-03-11T09:00:51.060 回答