publicstaticclassProgram { publicstaticasync Task<int> Main(string[] args) { var fileOption = new Option<FileInfo?>(name: "--file", description: "The file to read and display on the console"); var rootCommand = new RootCommand("Sample app for System.CommandLine"); rootCommand.AddOption(fileOption); rootCommand.SetHandler(file => { if (file != null) ReadFile(file); }, fileOption);
publicstaticclassProgram { publicstaticasync Task<int> Main(string[] args) { var fileOption = new Option<FileInfo?>(name: "--file", description: "The file to read and display on the console"); var delayOption = new Option<int>(name: "--delay", description: "Delay between lines, specified as milliseconds per character in a line.", getDefaultValue: () => 42);
var fgColorOption = new Option<ConsoleColor>(name: "--fgcolor", description: "Foreground color of text displayed on the console.", getDefaultValue: () => ConsoleColor.White);
var lightModeOption = new Option<bool>(name: "--light-mode", description: "Background color of text displayed on the console: default is black, light mode is white.");
var rootCommand = new RootCommand("Sample app for System.CommandLine"); var readCommand = new Command("read", "Reads a file and displays it on the console") { fileOption, delayOption, fgColorOption, lightModeOption }; rootCommand.AddCommand(readCommand);
// ... var fileOption = new Option<FileInfo?>(description: "The file to read and display on the console", name: "--file", isDefault: true, parseArgument: GetFileInfo);
rootCommand.AddGlobalOption(fileOption); var readCommand = new Command("read", "Reads a file and displays it on the console") { delayOption, fgColorOption, lightModeOption };
定义 quote Command,并将 readCommand 作为其 Sub Command:
1 2 3
var quotesCommand = new Command("quotes", "Work with a file that contains quotes."); quotesCommand.AddCommand(readCommand); rootCommand.AddCommand(quotesCommand);
var searchTermsOption = new Option<string[]>(name: "--search-terms", description: "Strings to search for when deleting entries.") {IsRequired = true, AllowMultipleArgumentsPerToken = true};
var deleteCommand = new Command("delete", "Deletes lines from a file."); deleteCommand.AddOption(searchTermsOption); deleteCommand.SetHandler((file, searchTerms) => DeleteFromFile(file!, searchTerms), fileOption, searchTermsOption);
var addCommand = new Command("add", "Add an entry to the file."); var quoteArgument = new Argument<string>(name: "quote", description: "Text of quote."); var bylineArgument = new Argument<string>(name: "byline", description: "Byline of quote.");