NetCore控制台實現自定義CommandLine功能


命令行科普:

例如輸入: trans 123 456 789 -r 123 -r 789
上面例子中:trans是Command,123 456 789是CommandArgument,-r之后的都是CommandOption.注意:命令行的格式是固定的
Command是必須的,CommandArgument和CommandOption都是可選的
只有設置了CommandArgument的multipleValues為true后,CommandArgument才可以接受多個參數,單個參數和多個參數可以通過CommandArgument.Values獲取
CommandOption設置了MultipleValue之后輸入格式必須為-option optionvalue -option optionvalue...

NetCore插件:McMaster.Extensions.CommandLineUtils,項目源碼:https://github.com/natemcmaster/CommandLineUtils

1、新建一個控制台項目

2、管理Nuget包。添加McMaster.Extensions.CommandLineUtils的引用

3、寫代碼

 1 using System;
 2 using System.Threading.Tasks;
 3 
 4 namespace Tree
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             CommandLine line = new CommandLine();
11             line.Run(args);
12         }
13     }
14 }
View Code
 1 using McMaster.Extensions.CommandLineUtils;
 2 
 3 namespace Tree
 4 {
 5     public class CommandLine
 6     {
 7         public void Run(string[] args)
 8         {
 9             CommandLineApplication app = new CommandLineApplication(false);
10             app.HelpOption("-?|-h|--help");
11             app.OnExecute(() =>
12             {
13                 app.ShowHelp();
14                 return 0;
15             });
16             app.Command("trans", command =>
17             {
18                 //var args1 = new[] { "Arg1", "arg with space", "args ' with \" quotes" };
19                 //Process.Start("echo", ArgumentEscaper.EscapeAndConcatenate(args1));
20                 string password = Prompt.GetPassword("please input your password: ");
21                 //Process.Start(DotNetExe.FullPathOrDefault(), "run");
22                 CommandArgument argument = command.Argument("[name]", "", multipleValues: true);
23                 CommandOption option = command.Option("-t", "this is a template", CommandOptionType.NoValue);
24                 command.OnExecute(() =>
25                 {
26                     if (option.Value() == "-t")
27                     {
28                         bool isRun = Prompt.GetYesNo("confirm your transaction, do your want to continue:", false);
29                         if (!isRun)
30                         {
31                             return;
32                         }
33                         command.Out.WriteLine($"密碼是{password}, 參數是:{argument}");
34                         return;
35                     }
36                 });
37             });
38             app.Execute(args);
39         }
40     }
41 }
View Code

4、結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM