【问题标题】:Using Return to end the app. Correct?使用 Return 结束应用程序。正确的?
【发布时间】:2010-09-24 14:48:52
【问题描述】:

我在 Main 方法的主体中有一个非常简单的应用程序。除了 Environment.Exit() 之外,我试图找出结束应用程序的不同方法,但我完全忘记了我可以调用 return。如果它只是在 Main 方法中运行,使用它来结束应用程序是否正确?我看不到任何问题,但我想尽可能多地学习。谢谢

【问题讨论】:

    标签: c# methods 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
    }
    

    【讨论】:

      【解决方案2】:

      如果您因错误而退出,您确实应该使用带有非零参数的Environment.Exit...记录哪种类型的错误返回哪个退出代码也是一个好主意。

      否则,只需 return... 应该没问题,但这确实是一种风格选择。

      【讨论】:

      • 你也可以声明Main返回int,并返回你的退出码。你不必打电话给Environment.Exit
      • @PDaddy:我不知道 C# 允许你这样做。哎呀。
      【解决方案3】:

      是的,从Main方法返回就可以了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        • 2023-01-25
        • 2014-10-18
        • 1970-01-01
        相关资源
        最近更新 更多