You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在System.CommandLine CLI中检查dry-run参数是否被传入

解决System.CommandLine获取dry-run选项值的问题

错误原因

你使用context.ParseResult.GetValueForOption<bool>("--dry-run")报错,是因为该方法要求传入Option对象实例,而非选项名称字符串。

解决方法

方法一:将Option存为类字段,直接引用实例

修改MyCommandClass,把dry-run选项定义为类的私有字段,让Handler通过命令实例获取该选项:

using System.CommandLine;
using Microsoft.Extensions.Logging;

namespace MyApp.Cli.commands;

public class MyCommandClass : Command 
{
    // 把选项定义为类字段
    private readonly Option<bool> _dryRunOption = new(new string[] { "--dry-run", "-d" }, "Simulate the actions without making any actual changes");

    public MyCommandClass()
        : base("start-my-command", "test the functionalities of system.commandline")
    {
        AddOption(_dryRunOption);
    }

    public new class Handler : ICommandHandler
    {
        private readonly ILogger<MyCommandClass> _log;
        private readonly MyCommandClass _command;

        // 注入命令实例以获取选项
        public Handler(ILogger<MyCommandClass> log, MyCommandClass command)
        {
            _log = log;
            _command = command;
        }

        public async Task<int> InvokeAsync(InvocationContext context)
        {
            // 通过选项实例获取值
            var isDryRun = context.ParseResult.GetValueForOption(_command._dryRunOption);

            if (isDryRun)
            {
                _log.LogInformation("is dry run");
            }
            else
            {
                _log.LogInformation("is no dry run");
            }

            return await Task.FromResult(0); // 返回命令退出码
        }
    }
}

方法二:使用属性绑定(推荐,代码更简洁)

System.CommandLine支持自动将选项值绑定到Handler的属性上,无需手动从ParseResult取值:

using System.CommandLine;
using Microsoft.Extensions.Logging;

namespace MyApp.Cli.commands;

public class MyCommandClass : Command 
{
    public MyCommandClass()
        : base("start-my-command", "test the functionalities of system.commandline")
    {
        AddOption(new Option<bool>(new string[] { "--dry-run", "-d" }, "Simulate the actions without making any actual changes"));
    }

    public new class Handler : ICommandHandler
    {
        private readonly ILogger<MyCommandClass> _log;

        // 定义与选项名称匹配的属性(名称需一致,或用[Option]特性指定对应关系)
        public bool DryRun { get; set; }

        public Handler(ILogger<MyCommandClass> log)
        {
            _log = log;
        }

        public async Task<int> InvokeAsync(InvocationContext context)
        {
            // 直接使用绑定后的属性值
            if (DryRun)
            {
                _log.LogInformation("is dry run");
            }
            else
            {
                _log.LogInformation("is no dry run");
            }

            return await Task.FromResult(0);
        }
    }
}

如果属性名称和选项名称不匹配,可给属性添加[Option("--dry-run")]特性明确指定对应关系。

方法三:通过ParseResult索引器获取(不推荐,类型不安全)

若不想修改类结构,也可通过索引器按选项名称取值,但需注意类型强制转换:

var isDryRun = (bool)context.ParseResult["--dry-run"].GetValueOrDefault();

这种方式缺乏类型安全校验,仅作为临时替代方案。

内容的提问来源于stack exchange,提问作者user21804110

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:42:40