Create our application by creating a CommandLineApplication, and configure the default app Name, Description, and enable HelpOption.
The HelpOption will be used for trigger the help output, the syntax of the string is self-explanatory: use either "-?", "-h" or "–help" as a parameter.
To make the default action to do something, we define the OnExecute with simple output Hello World.
To create a command, use app.Command(name, Func<cmd>) to define the action and configure arguments in the command function.
app.Command("hide", (command) =>{command.Description="Instruct the ninja to hide in a specific location.";command.HelpOption("-?|-h|--help");var locationArgument =command.Argument("[location]","Where the ninja should hide.");command.OnExecute(() => {var location =!string.IsNullOrWhiteSpace(locationArgument.Value)?locationArgument.Value:"under a turtle";Console.WriteLine("hide has finished. ninja hide "+ location);return0; });});
To create command argument that accept for multiple option values, we can use CommandOptionType.MultipleValue while configure in command.Option.
In the sample code below, you can exclude multiple attack target. For example: $ ninja attack -e dragons -e animals
app.Command("attack", (command) =>{command.Description="Instruct the ninja to go and attack!";command.HelpOption("-?|-h|--help"); // multiple commnad: -e | --exclude var excludeOption =command.Option("-e|--exclude <exclusions>","Things to exclude while attacking.",CommandOptionType.MultipleValue); // single commnad: -s | --scream var screamOption =command.Option("-s|--scream","Scream while attacking",CommandOptionType.NoValue);command.OnExecute(() => {var exclusions =excludeOption.Values;var attacking = (newList<string> {"dragons","badguys","civilians","animals" }) .Where(x =>!exclusions.Contains(x));Console.Write("Ninja is attacking "+string.Join(", ", attacking));if (screamOption.HasValue()) {Console.Write(" while screaming"); }Console.WriteLine();return0; });});
$ninjahideNinjaishiddenunderaturtle$ninjahide"on top of a street lamp"Ninjaishiddenontopofastreetlamp$ninjahide--helpUsage:ninjahide [arguments] [options]Arguments: [location] Wheretheninjashouldhide.Options:-?|-h|--helpShowhelpinformation