2010-09-24 57 views
0

我在Main方法的主體中有非常簡單的應用程序。我試圖找出除了Environment.Exit()之外的結束應用程序的不同方式,但我完全忘記了我只能調用return。如果它只是在Main方法中運行,使用它來結束應用程序是否正確?我看不出任何問題,但我想盡可能多地學習。謝謝使用Return結束應用程序。正確?

回答

1

沒錯,聽起來像你在正確的軌道上。目前還不清楚您是否正在運行控制檯應用程序,並且此代碼應該有助於突出顯示。

static void Main(string[] args) 
{ 
    bool keepRunning = true; 
    int x = 0; 
    while (keepRunning) 
    { 
     //at some point, flip keepRunning to fall out of the while loop 
     if (moon.Color == Blue) 
      keepRunning = false; 

     if (x > 0) //or some other condition 
      return; 
    } 
    //naturally will fall out of the Main() and terminate the program 
} 
1

如果你退出了,由於一個錯誤,你真的應該使用Environment.Exit與非零參數...記錄錯誤返回的是什麼類型的退出代碼是一個好主意,太。

否則,只需要return即可......但它確實是一種文體選擇。

+1

你也可以聲明'Main'來返回'int',並返回你的退出代碼。你不必調用'Environment.Exit'。 – 2010-09-24 15:04:00

+0

@PDaddy:我不知道C#讓你這樣做。哎呦。 – Powerlord 2010-09-24 15:23:33

0

是的,可以從Main方法返回。