代码之家  ›  专栏  ›  技术社区  ›  watkipet

如何使用System将布尔标志选项添加到命令中。命令行?

  •  1
  • watkipet  · 技术社区  · 1 年前

    我正在尝试将布尔标志选项添加到 System.CommandLine CNET程序。但是,当我运行程序时,我指定的任何内容似乎都不会导致 true 我的命令处理程序中的值:

    using System.CommandLine;
    using System.CommandLine.Parsing;
    using System.CommandLine.Builder;
    using System.CommandLine.NamingConventionBinder;
    
    var rootCommand = new RootCommand
    {
      Description = "System.CommandLine Example"
    };
    
    var exampleOption = new Option<bool>(
      new[] { "--opt", "-o" },
      "Set an example boolean option to true"
    );
    
    var exampleCommand = new Command("command", "Example command")
    {
      Handler = CommandHandler.Create<bool>((flag) =>
      {
        Console.WriteLine($"Ran example command with opt={flag}");
      })
    };
    
    
    exampleCommand.AddOption(exampleOption);
    rootCommand.AddCommand(exampleCommand);
    
    var parser = new CommandLineBuilder(rootCommand)
      .UseHelp()
      .UseDefaults()
      .Build();
    
    await parser.InvokeAsync(args);
    

    当我调用它时,我会得到以下结果:

    SystemCommandLineExample.exe command --opt=true
    Ran example command with opt=False
    

    我做错了什么?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Jon Skeet    1 年前

    这是因为您使用了命名约定绑定器,但与命名不一致。您已指定选项名称为 opt ,但您的参数被调用 flag 。如果您只是将命令更改为此命令,它会起作用:

    var exampleCommand = new Command("command", "Example command")
    {
        Handler = CommandHandler.Create<bool>((bool opt) =>
        {
            Console.WriteLine($"Ran example command with opt={opt}");
        })
    };
    

    来自 documentation :

    默认约定是参数按名称匹配,因此在以下示例中,选项 --an-int 与名为的参数匹配 anInt 。匹配会忽略连字符(以及其他选项前缀,如“/”),并且不区分大小写。