我非常熟悉命令行参数以及如何使用它们,但我以前从未处理过选项(或标志)。我指的是以下内容:
$ sort -f -s -u letters.txt
在上面的bash脚本示例中,我们有3个选项或标志,后跟常规参数。我想在C#应用程序中做类似的事情。处理命令行选项的最佳方法是什么,其中参数可以通过以下形式给出?
$ prog [-options] [args...]
答案 0 :(得分:7)
我建议使用Command Line Parser这样的库来处理这个问题。它支持开箱即用的verb commands可选参数,例如你的例子。
答案 1 :(得分:1)
我建议你尝试使用NDesk.Options ;,这是一个“基于回调的C#程序选项解析器”。
OptionSet目前支持:
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.
以下是docs:
的示例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;
}
答案 2 :(得分:0)
我使用my own。它很简单并且完成了工作(对我而言)。