在 C# 中解析命令行参数的最佳方法? [英] Best way to parse command line arguments in C#?

查看:26
本文介绍了在 C# 中解析命令行参数的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When building console applications that take parameters, you can use the arguments passed to Main(string[] args).

过去我只是简单地索引/循环该数组并执行一些正则表达式来提取值.然而,当命令变得更复杂时,解析会变得非常难看.

In the past I've simply indexed/looped that array and done a few regular expressions to extract the values. However, when the commands get more complicated, the parsing can get pretty ugly.

所以我很感兴趣:

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

假设命令始终遵循通用标准,例如 已回答这里.

Assume the commands always adhere to common standards such as answered here.

推荐答案

我强烈建议使用 NDesk.Options(文档)和/或 Mono.Options(相同的 API,不同的命名空间).文档中的示例:

I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace). An example from the documentation:

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.
" + 
          "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;
}

这篇关于在 C# 中解析命令行参数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆