协慌网

登录 贡献 社区

在 C#中解析命令行参数的最佳方法?

构建带参数的控制台应用程序时,可以使用传递给Main(string[] args)的参数Main(string[] args)

在过去,我只是索引 / 循环该数组并完成一些正则表达式来提取值。但是,当命令变得更复杂时,解析会非常难看。

所以我对以下内容感兴趣:

  • 您使用的库
  • 您使用的模式

假设命令始终遵循通用标准,例如此处的答案

答案

我强烈建议使用NDesk.OptionsDocumentation )和 / 或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);