2012-11-13 22 views
0

當我執行myExe.exe時,下面的默認功能沒有被執行,但是當我運行myExe.exe -launch時,它正在執行。任何想法爲什麼這個應用程序默認情況下不執行?按照Documentation這應該工作控制檯應用程序沒有參數時,默認方法不執行

摘自文檔:

As a fallback, a default handler may be registered which will handle all arguments which are not handled by any of the above matching algorithms. The default handler is designated by the name <> (which may be an alias for another named NDesk.Options.Option). 

我的代碼:

public static void Main (string[] args) 
{ 
    bool showHelp = false; 
    var options = new OptionSet() { 
     { 
      "h", "Show help", 
      v => showHelp = true 
     }, { 
      "config", "Reconfigure the launcher with different settings", 
      v => PromptConfig() 
     }, { 
      "v", "Show current version", 
      v => ShowVersion() 
     }, { 
      "launch", 
      v => LaunchApplication() 
     }, { 
      "<>", //default 
      v => LaunchApplication() 
     } 
    }; 

    //handle arguments 
    List<string> extra; 
    try { 
     extra = options.Parse (args); 
    } 
    catch (OptionException e) { 
     Console.Write("MyApp:"); 
     Console.WriteLine(e.Message); 
     Console.WriteLine("Try `MyApp--help' for more information"); 
     return; 
    } 

    if (showHelp) { 
     ShowHelp(options); 
     return; 
    } 
} 
+0

什麼*不*執行?看起來它工作正常,但不知道'options.Parse'的細節 –

+0

'LaunchApplication()'是當沒有參數傳遞時沒有運行的東西。 我不確定什麼.Parse看起來像是在這裏找到的NDesk.Options系統:http://www.ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html – Webnet

回答

1

默認的處理程序是設計來處理,而您並沒有提供具體的任何參數處理程序。

在你的情況下,運行MyExe.exe不應該調用默認處理程序,因爲沒有處理參數。如果你運行一個命令行如MyExe.exe -someUnknownArgument然後默認的處理程序應該一命嗚呼

反正我信了Parse方法的目的是幫助你解析命令行和初始化自己的模型表示的參數,然後對他們採取行動。

因此,舉例來說,你的代碼可能是這樣的:

public enum Action 
{ 
    ShowHelp, 
    ShowVersion, 
    PromptConfig, 
    LaunchApplication 
} 

public static void Main (string[] args) 
{ 
    var action = Action.LaunchApplication; 

    var options = new OptionSet() { 
     { 
      "h", "Show help", 
      v => action = Action.ShowHelp 
     }, 
     { 
      "config", "Reconfigure the launcher with different settings", 
      v => action = Action.PromptConfig 
     }, 
     { 
      "v", "Show current version", 
      v => action = Action.ShowVersion 
     }, 
     { 
      "launch", 
      v => action = Action.LaunchApplication 
     } 
    } 

    try 
    { 
     // parse arguments 
     var extra = options.Parse(args); 

     // act 
     switch (action) 
     { 
      // ... cases here to do the actual work ... 
     } 
    } 
    catch (OptionException e) 
    { 
     Console.WriteLine("MyApp: {0}", e.Message); 
     Console.WriteLine("Try `MyApp --help' for more information"); 
    } 
} 
相關問題