使用 Return 来结束应用程序。正确的?

发布于 2024-09-24 18:59:41 字数 147 浏览 4 评论 0原文

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

I have very simple application just in the body of Main method. I have tried to find out different ways of ending the app except for Environment.Exit() but I entirely forgot I can just call return. Is it correct to use it for ending the app if it just run in Main method? I cannot see any problem but I want to learn as much as I can. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

三寸金莲 2024-10-01 18:59:41

是的,听起来你走在正确的轨道上。目前尚不清楚您是否正在运行控制台应用程序,此代码应该有助于突出显示。

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
}

Right, sounds like you're on the right track. It's not clear if you're running a console application, and this code should help highlight.

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
}
蝶舞 2024-10-01 18:59:41

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

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

If you're exiting out due to an error, you really should use Environment.Exit with a non-zero argument... documenting what type of error returns which exit code is a good idea, too.

Otherwise, it should be OK to just return... but it's really a stylistic choice.

浊酒尽余欢 2024-10-01 18:59:41

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

Yes, it is OK to return from the Main method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文