2

基本上,我知道在命令行中使用“/?”调用某些应用程序时 从命令行返回如何使用参数调用应用程序的格式化列表。此外,这些应用程序有时甚至会弹出一个框,提醒用户程序只能在传入某些参数的情况下运行,并给出详细的格式化参数(类似于命令提示符输出)。

他们是怎么做到的(/?对我来说比弹出框更重要)?

4

2 回答 2

6

Main方法采用string[]命令行参数作为参数。
您也可以调用该Environment.GetCommandLineArgs方法

然后,您可以检查数组是否包含"/?".

于 2010-09-22T14:55:45.847 回答
2

尝试查看NDesk.Options。它是一个提供参数解析的单一源文件可嵌入 C# 库。您可以快速解析您的论点:

public static void Main(string[] args)
{
   string data = null;
   bool help   = false;
   int verbose = 0;

   var p = new OptionSet () {
      { "file=",     "The {FILE} to work on",             v => data = v },
      { "v|verbose", "Prints out extra status messages",  v => { ++verbose } },
      { "h|?|help",  "Show this message and exit",        v => help = v != null },
   };
   List<string> extra = p.Parse(args);
}

它也可以轻松地以专业的格式写出帮助屏幕:

if (help)
{
   Console.WriteLine("Usage: {0} [OPTIONS]", EXECUTABLE_NAME);
   Console.WriteLine("This is a sample program.");
   Console.WriteLine();
   Console.WriteLine("Options:");
   p.WriteOptionDescriptions(Console.Out);
}

这给出了这样的输出:

C:\>program.exe /?
Usage: program [OPTIONS]
This is a sample program.

Options:
  -file, --file=FILE         The FILE to work on
  -v, -verbose               Prints out extra status messages
  -h, -?, --help             Show this message and exit
于 2010-09-22T15:45:51.757 回答