【问题标题】:Command line Parser parses value eventhoug its not specified?命令行解析器解析值即使未指定?
【发布时间】:2021-03-11 08:12:34
【问题描述】:

我已经开始使用这个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:

但这总是触发parsedFunc,并且由于两个参数的值都是null,我的内部方法失败了吗?

我也尝试将选项更改为不需要,然后在控制台窗口中抛出一个错误,这些参数没有被指定,但触发了正确的方法。

【问题讨论】:

  • 由于建议阅读文档是违反网站规则的...根据参数名称,它看起来像 nonParsedFunc 只会在出现错误的情况下被调用(可能会找到您尚未定义的参数)和不是在缺少可选参数时...

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


【解决方案1】:

来自documentation

如果解析成功,您将获得派生的 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);
}

【讨论】:

  • 我喜欢这种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
相关资源
最近更新 更多