在C#中解析命令行参数的最佳方法?
构建接受参数的控制台应用程序时,可以使用传递给Main(string[] args)
。
在过去,我只是索引/循环该数组,并完成了一些正则表达式来提取值。 但是,当命令变得更复杂时,解析会变得非常难看。
所以我很感兴趣:
假设这些命令总是遵循通用标准,如在这里回答。
我强烈建议使用NDesk.Options(Documentation)和/或Mono.Options(相同的API,不同的名称空间)。 文档中的一个例子:
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;
}
我非常喜欢Command Line Parser Library(http://commandline.codeplex.com/)。 它具有通过属性设置参数的非常简单和优雅的方式:
class Options
{
[Option("i", "input", Required = true, HelpText = "Input file to read.")]
public string InputFile { get; set; }
[Option(null, "length", HelpText = "The maximum number of bytes to process.")]
public int MaximumLenght { get; set; }
[Option("v", null, HelpText = "Print details during execution.")]
public bool Verbose { get; set; }
[HelpOption(HelpText = "Display this help screen.")]
public string GetUsage()
{
var usage = new StringBuilder();
usage.AppendLine("Quickstart Application 1.0");
usage.AppendLine("Read user manual for usage instructions...");
return usage.ToString();
}
}
WPF TestApi库为C#开发提供了最好的命令行解析器之一。 我强烈建议从Ivo Manolov关于API的博客上进行研究:
// EXAMPLE #2:
// Sample for parsing the following command-line:
// Test.exe /verbose /runId=10
// This sample declares a class in which the strongly-
// typed arguments are populated
public class CommandLineArguments
{
bool? Verbose { get; set; }
int? RunId { get; set; }
}
CommandLineArguments a = new CommandLineArguments();
CommandLineParser.ParseArguments(args, a);
链接地址: http://www.djcxy.com/p/5149.html