在构建接受参数的控制台应用程序时,可以使用传递给Main的参数(string[] args)。
在过去,我只是简单地索引/循环该数组,并做了一些正则表达式来提取值。然而,当命令变得更加复杂时,解析就会变得非常糟糕。
我感兴趣的是:
你使用的库 你使用的模式
假设命令总是遵循常见的标准,比如这里回答的。
在构建接受参数的控制台应用程序时,可以使用传递给Main的参数(string[] args)。
在过去,我只是简单地索引/循环该数组,并做了一些正则表达式来提取值。然而,当命令变得更加复杂时,解析就会变得非常糟糕。
我感兴趣的是:
你使用的库 你使用的模式
假设命令总是遵循常见的标准,比如这里回答的。
当前回答
我非常喜欢命令行解析器库(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();
}
}
其他回答
http://www.codeplex.com/commonlibrarynet上有一个命令行参数解析器
它可以使用 1. 属性 2. 显式的调用 3.单行多个参数或字符串数组
它可以处理以下事情:
-config:Qa -startdate:${today} -region:'New York' Settings01
它很容易使用。
我强烈建议使用NDesk。选项(文档)和/或Mono。选项(相同的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;
}
CLAP(命令行参数解析器)有一个可用的API,并且有很好的文档。创建一个方法,注释参数。https://github.com/adrianaisemberg/CLAP
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);
我喜欢这个,因为你可以为参数“定义规则”,不管是否需要,……
或者如果你是一个Unix的家伙,那么你可能会喜欢GNU Getopt . net端口。