场景:我们在网上下载了一个第三方的软件(比如Nodejs),安装之后就可以再控制台输入命令,操作程序运行。这就是自定义CommandLine功能
NetCore插件:McMaster.Extensions.CommandLineUtils,项目源码:https://github.com/natemcmaster/CommandLineUtils
1、新建一个控制台项目
2、管理Nuget包。添加McMaster.Extensions.CommandLineUtils的引用
3、写代码
1 using System; 2 3 namespace Tree 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 string userCommand = ""; 10 while (userCommand.ToLower() != "exit") 11 { 12 userCommand = Console.ReadLine(); 13 string[] input = userCommand.Split(" "); 14 CoreOptions.Run(input); 15 } 16 Console.ReadKey(); 17 } 18 } 19 }
1 using McMaster.Extensions.CommandLineUtils; 2 3 namespace Tree 4 { 5 public class CoreOptions 6 { 7 public static void Run(string[] args) 8 { 9 CommandLineApplication app = new CommandLineApplication(false) 10 { 11 Name = "Tree", 12 Description = "Custom command line command." 13 }; 14 app.HelpOption("-h|--help"); 15 CommandArgument pathArgument = app.Argument("args", "params"); 16 17 CommandOption numberOption = app.Option("-p|--options", "command option", CommandOptionType.SingleOrNoValue); 18 19 app.OnExecute(() => 20 { 21 if (numberOption.HasValue()) 22 { 23 app.Out.WriteLine("write your logic, this is just a test"); 24 } 25 // you can add more else if to judge all command 26 else 27 { 28 app.Out.WriteLine("No such command"); 29 } 30 }); 31 app.Execute(args); 32 } 33 } 34 }
结果