C# 命令行参数
最后修改于 2023 年 7 月 5 日
在本文中,我们将展示如何在 C# 中使用命令行参数。
命令行参数是传递给控制台程序的值,通常通过终端传递。
我们可以通过声明一个类型为 string[] 的参数,将命令行参数发送到 Main 方法。 使用顶级语句的程序有一个默认的内置 args 变量,其中包含参数。
C# Main 方法中的命令行参数
在第一个示例中,我们将命令行参数传递给 Main 方法。
Program.cs
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}
在该程序中,我们只是将所有参数打印到控制台。
static void Main(string[] args)
命令行参数具有 string[] 类型。 按照惯例,将变量命名为 args。
$ dotnet run John Doe gardener John Doe gardener
C# 没有 Main 方法的命令行参数
如果没有 Main 方法,则可以通过内置变量 args 访问参数。
Program.cs
Console.WriteLine($"You have passed {args.Length} arguments");
foreach (var arg in args)
{
Console.WriteLine(arg);
}
该程序打印命令行参数的数量并将它们打印到终端。
$ dotnet run 1 2 3 4 5 6 You have passed 6 arguments 1 2 3 4 5 6
C# Environment.GetCommandLineArgs
Environment.GetCommandLineArgs 返回一个字符串数组,其中包含当前进程的命令行参数。
Program.cs
string[] cargs = Environment.GetCommandLineArgs();
Console.WriteLine($"You have passed {cargs.Length} arguments");
foreach (var arg in cargs)
{
Console.WriteLine(arg);
}
它比默认的内置变量 args 更明确。 此外,Environment.GetCommandLineArgs 将程序名称计为其中一个参数。
$ dotnet run 1 2 3 4 5 You have passed 6 arguments /home/jano/Documents/prog/csharp/cmd-args/SimpleEx/bin/Debug/net6.0/SimpleEx.dll 1 2 3 4 5
C# Environment.CommanLine
Environment.CommanLine 返回一个包含命令行参数的字符串。
Program.cs
string cargs = Environment.CommandLine;
Console.WriteLine(cargs);
string[] vals = cargs.Split(" ");
try
{
int sum = vals.Skip(1).Select(e => Convert.ToInt32(e)).Sum();
Console.WriteLine($"The sum of values is {sum}");
return 0;
}
catch (FormatException e)
{
Console.WriteLine("Invalid input");
Console.WriteLine(e.Message);
return 1;
}
该程序期望一个整数列表作为输入。
string cargs = Environment.CommandLine;
我们使用 Environment.CommandLine 获取命令行输入。
string[] vals = cargs.Split(" ");
我们将字符串拆分为多个部分。
int sum = vals.Skip(1).Select(e => Convert.ToInt32(e)).Sum();
我们跳过第一个参数,即程序名称。 我们将字符串转换为整数并计算总和。
catch (FormatException e)
{
解析命令行参数容易出错。 我们可能会得到 FormatExceptions。
C# CommandLineParser
命令行解析器库提供了一个简洁明了的 API 来操作命令行参数。
$ dotnet add package CommandLineParser
我们添加 CommandLineParser 包。
Program.cs
namespace CommandLineArgs;
using CommandLine;
class Options
{
[Option("vals")]
public IEnumerable<int>? Vals { get; set; }
}
class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args).WithParsed<Options>(o =>
{
if (o.Vals != null)
{
int sum = o.Vals.Sum();
Console.WriteLine($"The sum is {sum}");
}
else
{
Console.WriteLine("No arguments");
}
});
}
}
该程序定义了一个 --vals 选项,它接受一个整数序列。
$ dotnet run --vals 1 2 3 4 5 6 The sum is 21
来源
在本文中,我们学习了如何在 C# 中使用命令行参数。
作者
列出所有 C# 教程。