如何在System.CommandLine命令处理器内调用帮助文本?
解决方案
要实现直接调用Barcode命令时显示帮助文本,无需额外注入依赖,直接利用InvocationContext提供的上下文资源即可完成。以下是修改后的BarcodeCommandHandler代码:
public class BarcodeCommandHandler : ICommandHandler { public bool List { get; set; } public int Invoke(InvocationContext context) { return InvokeAsync(context).GetAwaiter().GetResult(); } public Task<int> InvokeAsync(InvocationContext context) { if (!List) { // 生成并输出当前命令的帮助文本 var helpBuilder = new HelpBuilder(context.Console, context.ParseResult.CommandResult.Command); helpBuilder.Write(context.ParseResult.CommandResult.Command); return Task.FromResult(0); // 返回0表示帮助显示成功 } // 执行--list对应的逻辑 Console.WriteLine("列出所有可用条码..."); return Task.FromResult(0); } }
关键说明:
- 无需额外DI注入:
InvocationContext已经包含了生成帮助所需的Console和当前Command实例,直接使用即可。 - HelpBuilder的作用:
HelpBuilder是System.CommandLine提供的帮助文本生成器,能自动根据命令的元数据(描述、选项、子命令等)生成标准化的帮助内容。 - 返回值处理:显示帮助后返回
0(成功状态码),符合命令行工具的常规行为;如果需要区分帮助显示和错误场景,也可以根据需求调整返回值。
扩展优化(可选)
如果后续命令结构更复杂(比如添加Generate子命令),可以通过检查ParseResult中是否存在子命令来更精准地控制帮助显示逻辑:
if (!List && context.ParseResult.CommandResult.Children.Count == 0) { // 既没有--list,也没有指定子命令时才显示帮助 var helpBuilder = new HelpBuilder(context.Console, context.ParseResult.CommandResult.Command); helpBuilder.Write(context.ParseResult.CommandResult.Command); return Task.FromResult(0); }
内容的提问来源于stack exchange,提问作者David Turley
相关产品推荐
相关产品推荐

