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# 中解析命令行参数的最佳方法是什么?
基础教程推荐
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
