Best way to handle command line options in C#
本问题已经有最佳答案,请猛点这里访问。
我非常熟悉命令行参数以及如何使用它们,但我以前从未处理过选项(或标志)。我指的是如下内容:
1 | $ sort -f -s -u letters.txt |
在上面的bash脚本示例中,我们有3个选项或标志,后面跟着常规参数。我想在C应用程序中做类似的事情。处理命令行选项的最佳方法是什么?在这些选项中,参数可以用以下形式给出?
1 | $ prog [-options] [args...] |
我建议使用命令行解析器之类的库来处理这个问题。它支持使用动词命令(如示例)的可选参数。
我建议您尝试使用ndesk.options;,它是一个"基于回调的C程序选项分析器"。
选项集当前支持:
1 2 3 4 5 | Boolean options of the form: -flag, --flag, and /flag. Boolean parameters can have a `+' or `-' appended to explicitly enable or disable the flag (in the same fashion as mcs -debug+). For boolean callbacks, the provided value is non-null for enabled, and null for disabled. Value options with a required value (append `=' to the option name) or an optional value (append `:' to the option name). The option value can either be in the current option (--opt=value) or in the following parameter (--opt value). The actual value is provided as the parameter to the callback delegate, unless it's (1) optional and (2) missing, in which case null is passed. Bundled parameters which must start with a single `-' and consists of a sequence of (optional) boolean options followed by an (optional) value-using option followed by the options's vlaue. In this manner, -abc would be a shorthand for -a -b -c, and -cvffile would be shorthand for -c -v -f=file (in the same manner as tar(1)). Option processing is disabled when -- is encountered. |
以下是文档中的一个示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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; } |
我用我自己的。这很简单,而且(对我)能完成任务。