在构建需要传递参数的控制台应用程序时,您可以使用传递给Main(string[] args)
的参数。
过去,我通常会对该数组进行索引/循环并执行一些正则表达式来提取值。 然而,当命令变得更加复杂时,解析可能会变得相当丑陋。
因此,我对以下内容感兴趣:
- 您使用的库
- 您使用的模式
假设命令始终遵循这里的公共标准。
在构建需要传递参数的控制台应用程序时,您可以使用传递给Main(string[] args)
的参数。
过去,我通常会对该数组进行索引/循环并执行一些正则表达式来提取值。 然而,当命令变得更加复杂时,解析可能会变得相当丑陋。
因此,我对以下内容感兴趣:
假设命令始终遵循这里的公共标准。
我强烈建议使用NDesk.Options(文档)和/或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;
}
git checkout master
这样操作),或者它们的参数不够灵活(即不支持 --foo 123
= --foo=123
= -f 123
= -f=123
和 -v -h
= -vh
)。 - Wernight我真的很喜欢命令行解析器库(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();
}
}
--recursive
。 - WernightWPF 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);
看起来每个人都有自己的命令行解析器,我也想添加自己的解析器 :).
这个库包含一个命令行解析器,可以使用命令行中的值来初始化某个类。它具有许多功能(我已经建立了很多年)。
从文档中可知...
BizArk框架中的命令行解析具有以下关键特点:
CLAP(命令行参数解析器)有一个易于使用的API并且文档描述非常清晰。您只需要编写一个方法,并注释参数即可。https://github.com/adrianaisemberg/CLAP
myapp myverb -argname argvalue
(必须有-argname
)或者 myapp -help
(通常是--help
)。 - Wernight有很多解决这个问题的方案。为了全面并提供选择,如果有人需要,我在我的谷歌代码库中添加了两个有用的类的答案。
第一个是ArgumentList,它仅负责解析命令行参数。它收集由开关“/x:y”或“-x=y”定义的名称-值对,并收集“未命名”的条目列表。它的基本用法在此处讨论,查看此类。
这个问题的第二部分是CommandInterpreter,它可以将你的.Net类创建为完全功能的命令行应用程序。例如:
using CSharpTest.Net.Commands;
static class Program
{
static void Main(string[] args)
{
new CommandInterpreter(new Commands()).Run(args);
}
//example ‘Commands’ class:
class Commands
{
public int SomeValue { get; set; }
public void DoSomething(string svalue, int ivalue)
{ ... }
通过以上示例代码,您可以运行以下内容:
Program.exe DoSomething "字符串值" 5
-- 或者 --
Program.exe dosomething /ivalue=5 -svalue:"字符串值"
您可能会喜欢我的一个工具 Rug.Cmd
这是一个易于使用且可扩展的命令行参数解析器。它可以处理:布尔值、加号/减号、字符串、字符串列表、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);
}
}
}
编辑:这是我的项目,因此本答案不应被视为第三方的认可。话虽如此,我确实在编写每个基于命令行的程序时都使用它,它是开源的,我希望其他人也能从中受益。