发布日期:2018-03-26
在C#中,解析命令行参数的最佳方式是什么?+ 查看更多
在C#中,解析命令行参数的最佳方式是什么?
+ 查看更多
发布日期:2018-03-07 14:01
分类:C#
浏览次数:104
当构建带参数的控制台应用程序时,你可以使用传递给 Main(string[] args) 函数的参数。
过去,我仅仅通过索引或循环遍历的方式从参数数组 args 中提取值。然而,当命令变得越来越复杂时,这种解析方式就会变得很笨拙。
所以,我对以下2点很感兴趣:
该使用那些库?
该使用什么样的处理方式?
该使用什么样的处理方式?
假定命令总是遵守通用的标准,例如 GNU 命令行标准 ,tar -zxvf filename。
回答
我强烈建议使用 NDesk.Options ( [[http://www.ndesk.org/doc/ndesk-options/]] )和/或者 Mono.Options (API接口一样,只是命名空间不同)。
这个文档中的一个例子:
bool show_help = false; Listnames = new List (); 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 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; }