使用System.CommandLine添加布尔标志选项无效?问题排查
问题:System.CommandLine布尔标志始终返回false
我正尝试在基于System.CommandLine的C#/.NET程序中添加一个布尔标志选项,但运行程序时无论指定什么参数,命令处理程序中始终无法得到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
请问我哪里出错了?
问题原因与解决方法
核心问题是命令处理程序的参数名与选项名称不匹配:
- 你定义的选项长名称是
--opt,对应的参数绑定名称是opt - 但处理程序中使用的参数名是
flag,NamingConventionBinder无法将选项值绑定到不匹配的参数上,因此始终使用布尔类型的默认值false
解决方法
将处理程序的参数名改为与选项名称一致的opt即可:
var exampleCommand = new Command("command", "Example command") { Handler = CommandHandler.Create<bool>((opt) => { Console.WriteLine($"Ran example command with opt={opt}"); }) };
补充说明
布尔类型的选项在System.CommandLine中默认是开关式标志,不需要赋值操作,直接输入--opt或-o即可将值设为true,比如:
SystemCommandLineExample.exe command --opt
这样也能正确输出Ran example command with opt=True
内容的提问来源于stack exchange,提问作者watkipet
相关产品推荐
相关产品推荐

