.net 如何在Microsoft System中检查特定参数,命令行CLI

0pizxfdo  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(124)

我目前正在使用软件包System.CommandLine配置CLI命令。
在我的CommandClass中,我添加了一个选项,让用户选择是否要执行dry-run。我如何检查用户是否给出了特定的参数?
我的代码片段:

using System.CommandLine;
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;

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

        public async Task<int> InvokeAsync(InvocationContext context)
        {
            var isDryRun = /* check if the user has provided the parameter "--dry-run" */

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

字符串
我已经尝试过做var isDryRun = context.ParseResult.GetValueForOption<bool>("--dry-run");,但这只是给了我以下错误:* 参数1:无法从'字符串'转换为'系统.命令行.选项'*。
请帮帮忙,谢谢。

r6vfmomb

r6vfmomb1#

与其使用context.ParseResult.GetValueForOption(“--dry-run”),不如直接引用在向命令添加选项时创建的Option对象。

public class MyCommandClass : Command 
{
    // Declaring the dry-run option at the class level
    private Option<bool> dryRunOpt = new Option<bool>(
        aliases: new[] { "--dry-run", "-d" },
        description: "Run in dry mode without actual changes"
    );

    public MyCommandClass() : base("start-my-command", "Testing the functionalities")
    {
        // Adding the dry-run option to our command
    // This line is important :)
        AddOption(dryRunOpt);
    }

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

        public Handler(ILogger<MyCommandClass> logger)
        {
            this.logger = logger;
        }

        public async Task<int> InvokeAsync(InvocationContext context)
        {
            // Checking the dry-run option value
            var isDryRun = context.ParseResult.GetValueForOption(dryRunOpt);

            if (isDryRun)
            {
                logger.LogInformation("Running in dry-run mode.");
            }
            else
            {
                logger.LogInformation("Executing normal operation.");
            }

            // ...

            return 0;
        }
    }
}

字符串

相关问题