McMaster.Extensions.CommandLineUtils 是我用过的最好的 c# 命令行解析器。我特别喜欢它很好地支持子命令。
源代码在这里:https ://github.com/natemcmaster/CommandLineUtils
dotnet add package McMaster.Extensions.CommandLineUtils
这是一个如何使用属性的简单示例:
using System;
using McMaster.Extensions.CommandLineUtils;
public class Program
{
public static int Main(string[] args)
=> CommandLineApplication.Execute<Program>(args);
[Option(Description = "The subject")]
public string Subject { get; } = "world";
[Option(ShortName = "n")]
public int Count { get; } = 1;
private void OnExecute()
{
for (var i = 0; i < Count; i++)
{
Console.WriteLine($"Hello {Subject}!");
}
}
}
或者您可以使用构建器:
using System;
using McMaster.Extensions.CommandLineUtils;
var app = new CommandLineApplication();
app.HelpOption();
var subject = app.Option("-s|--subject <SUBJECT>", "The subject", CommandOptionType.SingleValue);
subject.DefaultValue = "world";
var repeat = app.Option<int>("-n|--count <N>", "Repeat", CommandOptionType.SingleValue);
repeat.DefaultValue = 1;
app.OnExecute(() =>
{
for (var i = 0; i < repeat.ParsedValue; i++)
{
Console.WriteLine($"Hello {subject.Value()}!");
}
});
return app.Execute(args);
微软也一直在开发命令行解析器:https ://github.com/dotnet/command-line-api ,但它已经预览了很久了。