我非常熟悉命令行参数以及如何使用它们,但我以前从未处理过选项(或标志)。我指的是以下内容:
$ sort -f -s -u letters.txt
在上面的 bash 脚本示例中,我们有 3 个选项或标志,后跟常规参数。我想在 C# 应用程序中做类似的事情。处理命令行选项的最佳方法是什么,其中参数可以以下列形式给出?
$ prog [-options] [args...]
我非常熟悉命令行参数以及如何使用它们,但我以前从未处理过选项(或标志)。我指的是以下内容:
$ sort -f -s -u letters.txt
在上面的 bash 脚本示例中,我们有 3 个选项或标志,后跟常规参数。我想在 C# 应用程序中做类似的事情。处理命令行选项的最佳方法是什么,其中参数可以以下列形式给出?
$ prog [-options] [args...]
我建议您尝试使用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.
这是文档中的一个示例:
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;
}
我用我自己的. 这很简单并且可以完成工作(对我来说)。