System.CommandLine 的核心优势是将命令行输入强类型映射为 C# 对象,支持 Option、Argument、子命令嵌套、自定义解析与验证,并通过泛型 Handler 实现零反射调用。

System.CommandLine 的核心优势是把命令行输入直接映射为 C# 对象,避免手动拆解 args 字符串。关键不是“怎么加参数”,而是“怎么让参数自动变成你想要的类型和结构”。
比如定义一个发布命令:myapp publish --project MyApp.csproj --configuration Release --output ./bin,你可以这样建模:
Option<string></string> 表示单值参数(如 --project),指定别名(-p)、描述、是否必需Option<ilist>></ilist> 支持多次出现的参数(如 --property Key=Value 可重复)Argument<string></string> 处理位置参数(如 myapp run api 中的 api)Handler 方法的参数上,System.CommandLine 自动完成转换和验证老式做法常依赖反射调用方法,而 System.CommandLine 推荐用强类型委托,既安全又高效。不用写 typeof(...).GetMethod(...).Invoke() 这类易错代码。
例如:
var publishCommand = new Command("publish", "Publish a .NET project");
publishCommand.AddOption(projectOption);
publishCommand.AddOption(configOption);
publishCommand.AddOption(outputOption);
<p>publishCommand.Handler = CommandHandler.Create<string, string, string>(PublishHandler);</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1319">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680201295703.jpg" alt="AI Undetect">
</a>
<div class="aritcle_card_info">
<a href="/ai/1319">AI Undetect</a>
<p>让AI无法察觉,让文字更人性化,为文字体验创造无限可能。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="AI Undetect">
<span>162</span>
</div>
</div>
<a href="/ai/1319" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="AI Undetect">
</a>
</div>
<p>// 方法签名完全匹配,自动注入解析后的值
static void PublishHandler(string project, string configuration, string output)
{
Console.WriteLine($"Publishing {project} in {configuration} to {output}");
}</p>注意:参数名必须和 Option.Argument.GetDefaultValue() 或绑定名一致;如果想用不同名,可用 Option<t>.Alias</t> 或 Option<t>.SetName()</t> 显式对齐。
真实 CLI 工具往往有层级,比如 git commit、git push。System.CommandLine 原生支持子命令嵌套,还能让多个子命令共用一组基础选项(如 --verbose、--dry-run)。
RootCommand.AddCommand(subCmd) 构建树形结构RootCommand,再通过 InvocationContext.ParseResult.GetValueForOption() 在各 handler 中按需读取Command.AddGlobalOption()(.NET 7+)自动下推到所有子命令ParseResult.FindResultFor() 可判断某个选项是否被显式传入(区别于默认值)当标准类型转换不够用(比如要解析自定义时间格式、枚举别名、文件路径存在性校验),System.CommandLine 允许你插入自己的转换器和验证器。
option.ParseArgument = result => { /* 自定义逻辑 */ } 替换默认解析option.AddValidator(opt => { if (...) return "Invalid format"; }) 提供友好错误提示CommandLineBuilder.UseExceptionHandler() 捕获 CommandException 等,并输出结构化帮助或退出码基本上就这些。System.CommandLine 的高级用法,核心是“声明即契约”——你定义的 Option、Argument、Handler 就是用户能输入什么、程序会收到什么、出错时反馈什么。不复杂但容易忽略的是:别急着写逻辑,先花十分钟把命令结构用对象模型画清楚。
以上就是C#怎么解析命令行参数 System.CommandLine库高级用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号