解析在C#中的命令行参数的最佳方法? [英] Best way to parse command line arguments in C#?
问题描述
在建设有参数的控制台应用程序,您可以使用传递给参数主要(字串[] args)
。
When building console applications that take parameters, you can use the arguments passed to Main(string[] args)
.
在过去,我只是索引/环状该数组,做一些常规的前pressions提取值。但是,当命令变得更加复杂,解析可以得到pretty难看。
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.
所以我很感兴趣:
- 您使用库
- 模式中使用
假设命令始终坚持共同的标准,如<一个href=\"http://stackoverflow.com/questions/108728/suggestions-for-implemetation-of-a-commnd-line-application-interface\">answered这里。
Assume the commands always adhere to common standards such as answered here.
推荐答案
我强烈建议使用 NDesk.Options (<一个HREF =http://www.ndesk.org/doc/ndesk-options/>文档)和/或<一个href=\"https://github.com/mono/mono/blob/master/mcs/class/Mono.Options/Mono.Options/Options.cs\">Mono.Options (相同的API,不同的命名空间)。一个<一个href=\"http://www.ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html#T%3aNDesk.Options.OptionSet%3aDocs%3aExample:1\">example从文档:
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.\n" +
"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#中的命令行参数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!