string[] args
是控制台程序中读取终端输入参数的方式。它作为 Main
方法的参数,用于接收从命令行传递过来的参数数组。下面详细说明 string[] args
的作用和使用方式。
作用
在终端中运行一个控制台程序时,可以传递多个参数给程序。例如,如果运行以下命令:
1
| MyApp.exe arg1 arg2 arg3
|
这些参数会传递给 Main
方法中的 args
数组,即:
1
| static void Main(string[] args)
|
在这个例子中,args
数组将包含以下内容:
1 2 3
| args[0] = "arg1" args[1] = "arg2" args[2] = "arg3"
|
使用示例
以下是一个简单的示例程序,展示如何使用 string[] args
读取和处理命令行参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| using System;
class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No arguments provided."); return; }
Console.WriteLine("Arguments received:"); foreach (var arg in args) { Console.WriteLine(arg); } } }
|
如果在终端中运行 MyApp.exe arg1 arg2 arg3
,程序会输出:
1 2 3 4
| Arguments received: arg1 arg2 arg3
|
实际应用
为了展示如何解析命令和参数,并执行相应的功能,以下是一个稍微复杂的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| using System;
class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: MyApp <command> <parameters>"); return; }
string command = args[0]; string[] parameters = args.Skip(1).ToArray();
switch (command.ToLower()) { case "greet": Greet(parameters); break; case "sum": Sum(parameters); break; default: Console.WriteLine($"Unknown command: {command}"); break; } }
static void Greet(string[] parameters) { if (parameters.Length < 1) { Console.WriteLine("Usage: MyApp greet <name>"); return; }
string name = parameters[0]; Console.WriteLine($"Hello, {name}!"); }
static void Sum(string[] parameters) { if (parameters.Length < 2) { Console.WriteLine("Usage: MyApp sum <num1> <num2>"); return; }
if (int.TryParse(parameters[0], out int num1) && int.TryParse(parameters[1], out int num2)) { Console.WriteLine($"Sum: {num1 + num2}"); } else { Console.WriteLine("Both parameters must be integers."); } } }
|
使用第三方库
为了更复杂的命令行参数解析,可以使用第三方库(如 CommandLineParser
)来简化处理过程。以下是使用 CommandLineParser
库的示例:
.Net安装 CommandLineParser
:
1
| dotnet add package CommandLineParser
|
然后,使用该库解析命令行参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| using System; using CommandLine;
class Program { static void Main(string[] args) { Parser.Default.ParseArguments<GreetOptions, SumOptions>(args) .MapResult( (GreetOptions opts) => Greet(opts), (SumOptions opts) => Sum(opts), errs => 1); }
static int Greet(GreetOptions opts) { Console.WriteLine($"Hello, {opts.Name}!"); return 0; }
static int Sum(SumOptions opts) { Console.WriteLine($"Sum: {opts.Num1 + opts.Num2}"); return 0; } }
class GreetOptions { [Value(0, MetaName = "name", Required = true, HelpText = "Name to greet.")] public string Name { get; set; } }
class SumOptions { [Value(0, MetaName = "num1", Required = true, HelpText = "First number.")] public int Num1 { get; set; }
[Value(1, MetaName = "num2", Required = true, HelpText = "Second number.")] public int Num2 { get; set; } }
|