在构建接受参数的控制台应用程序时,可以使用传递给Main的参数(string[] args)。
在过去,我只是简单地索引/循环该数组,并做了一些正则表达式来提取值。然而,当命令变得更加复杂时,解析就会变得非常糟糕。
我感兴趣的是:
你使用的库 你使用的模式
假设命令总是遵循常见的标准,比如这里回答的。
在构建接受参数的控制台应用程序时,可以使用传递给Main的参数(string[] args)。
在过去,我只是简单地索引/循环该数组,并做了一些正则表达式来提取值。然而,当命令变得更加复杂时,解析就会变得非常糟糕。
我感兴趣的是:
你使用的库 你使用的模式
假设命令总是遵循常见的标准,比如这里回答的。
当前回答
请使用apache commons cli API的。net端口。这很有效。
http://sourceforge.net/projects/dotnetcli/
以及用于概念和介绍的原始API
http://commons.apache.org/cli/
其他回答
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://github.com/mono/mono/tree/master/mcs/class/Mono.Options/
你可能会喜欢我的地毯。Cmd
易于使用和扩展的命令行参数解析器。句柄:Bool,加/减,字符串,字符串列表,CSV,枚举。
内置/?帮助模式。
内置/??'和'/?D'文档生成器模式。
static void Main(string[] args)
{
// create the argument parser
ArgumentParser parser = new ArgumentParser("ArgumentExample", "Example of argument parsing");
// create the argument for a string
StringArgument StringArg = new StringArgument("String", "Example string argument", "This argument demonstrates string arguments");
// add the argument to the parser
parser.Add("/", "String", StringArg);
// parse arguemnts
parser.Parse(args);
// did the parser detect a /? argument
if (parser.HelpMode == false)
{
// was the string argument defined
if (StringArg.Defined == true)
{
// write its value
RC.WriteLine("String argument was defined");
RC.WriteLine(StringArg.Value);
}
}
}
编辑:这是我的项目,因此这个答案不应该被视为来自第三方的认可。也就是说,我确实在我编写的每个基于命令行的程序中使用它,它是开源的,我希望其他人可以从中受益。
c# CLI是我编写的一个非常简单的命令行参数解析库。它是有据可查的开源软件。
我以前写过一个c#命令行参数解析器。网址:http://www.codeplex.com/CommandLineArguments