Best way to parse command line arguments in C#?(在 C# 中解析命令行参数的最佳方法是什么?)
问题描述
在构建带参数的控制台应用程序时,您可以使用传递给 Main(string[] args)
的参数.
When building console applications that take parameters, you can use the arguments passed to Main(string[] args)
.
在过去,我只是简单地索引/循环该数组并使用一些正则表达式来提取值.但是,当命令变得更复杂时,解析会变得非常难看.
In the past I've simply indexed/looped that array and done a few regular expressions to extract the values. However, when the commands get more complicated, the parsing can get pretty ugly.
所以我对:
- 您使用的库
- 您使用的模式
假设命令始终遵守通用标准,例如 已回答这里.
Assume the commands always adhere to common standards such as answered here.
推荐答案
我强烈建议使用 NDesk.Options(文档)和/或 Mono.Options(相同的 API,不同的命名空间).一个 文档中的示例:
I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace). An example from the documentation:
bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;
var p = new OptionSet () {
{ "n|name=", "the {NAME} of someone to greet.",
v => names.Add (v) },
{ "r|repeat=",
"the number of {TIMES} to repeat the greeting.
" +
"this must be an integer.",
(int v) => repeat = v },
{ "v", "increase debug message verbosity",
v => { if (v != null) ++verbosity; } },
{ "h|help", "show this message and exit",
v => show_help = v != null },
};
List<string> extra;
try {
extra = p.Parse (args);
}
catch (OptionException e) {
Console.Write ("greet: ");
Console.WriteLine (e.Message);
Console.WriteLine ("Try `greet --help' for more information.");
return;
}
这篇关于在 C# 中解析命令行参数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中解析命令行参数的最佳方法是什么?


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01