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

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

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

  1. using System.CommandLine;
  2. namespace MyApp.Cli.commands;
  3. public class MyCommandClass : Command
  4. {
  5. public MyCommandClass()
  6. : base("start-my-command", "test the functionalities of system.commandline")
  7. {
  8. AddOption(new Option<bool>(new string[] { "--dry-run", "-d" }, "Simulate the actions without making any actual changes"));
  9. }
  10. public new class Handler : ICommandHandler
  11. {
  12. private readonly ILogger<MyCommandClass> _log;
  13. public Handler(ILogger<MyCommandClass> log)
  14. {
  15. _log = log;
  16. }
  17. public async Task<int> InvokeAsync(InvocationContext context)
  18. {
  19. var isDryRun = /* check if the user has provided the parameter "--dry-run" */
  20. if (isDryRun)
  21. {
  22. _log.LogInformation("is dry run");
  23. }
  24. else
  25. {
  26. _log.LogInformation("is no dry run");
  27. }
  28. }
  29. }
  30. }

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

r6vfmomb

r6vfmomb1#

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

  1. public class MyCommandClass : Command
  2. {
  3. // Declaring the dry-run option at the class level
  4. private Option<bool> dryRunOpt = new Option<bool>(
  5. aliases: new[] { "--dry-run", "-d" },
  6. description: "Run in dry mode without actual changes"
  7. );
  8. public MyCommandClass() : base("start-my-command", "Testing the functionalities")
  9. {
  10. // Adding the dry-run option to our command
  11. // This line is important :)
  12. AddOption(dryRunOpt);
  13. }
  14. public class Handler : ICommandHandler
  15. {
  16. private readonly ILogger<MyCommandClass> logger;
  17. public Handler(ILogger<MyCommandClass> logger)
  18. {
  19. this.logger = logger;
  20. }
  21. public async Task<int> InvokeAsync(InvocationContext context)
  22. {
  23. // Checking the dry-run option value
  24. var isDryRun = context.ParseResult.GetValueForOption(dryRunOpt);
  25. if (isDryRun)
  26. {
  27. logger.LogInformation("Running in dry-run mode.");
  28. }
  29. else
  30. {
  31. logger.LogInformation("Executing normal operation.");
  32. }
  33. // ...
  34. return 0;
  35. }
  36. }
  37. }

字符串

展开查看全部

相关问题