为什么控制台窗口在显示我的输出后立即关闭? [英] Why is the console window closing immediately once displayed my output?

查看:37
本文介绍了为什么控制台窗口在显示我的输出后立即关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照 MSDN 中的指南学习 C#.

I'm studying C# by following the guides in MSDN.

现在,我刚刚尝试了示例 1(这里MSDN 的链接),我遇到了一个问题:为什么控制台窗口在显示我的输出后立即关闭?

Now, I just tried the Example 1 (here is the link to MSDN), and I've encountered an issue: why is the console window closing immediately once displayed my output?

using System;

public class Hello1
{
    public static int Main()
    {
        Console.WriteLine("Hello, World!");
        return 0;
    }
}

推荐答案

这里的问题是他们的 Hello World 程序正在显示,然后它会立即关闭.
这是为什么?

the issue here is that their Hello World Program is showing up then it would immediately close.
why is that?

因为它完成了.当控制台应用程序完成执行并从它们的 main 方法返回时,相关的控制台窗口会自动关闭.这是预期的行为.

Because it's finished. When console applications have completed executing and return from their main method, the associated console window automatically closes. This is expected behavior.

如果您想保持打开以进行调试,您需要指示计算机在结束应用程序和关闭窗口之前等待按键按下.

If you want to keep it open for debugging purposes, you'll need to instruct the computer to wait for a key press before ending the app and closing the window.

Console.ReadLine 方法 是一种方法.将此行添加到代码末尾(就在 return 语句之前)将导致应用程序在退出之前等待您按下某个键.

The Console.ReadLine method is one way of doing that. Adding this line to the end of your code (just before the return statement) will cause the application to wait for you to press a key before exiting.

或者,您可以通过在 Visual Studio 环境中按 Ctrl+F5 来启动没有附加调试器的应用程序,但这有一个明显的缺点,即阻止您使用调试功能,您在编写应用程序时可能希望使用这些功能.

Alternatively, you could start the application without the debugger attached by pressing Ctrl+F5 from within the Visual Studio environment, but this has the obvious disadvantage of preventing you from using the debugging features, which you probably want at your disposal when writing an application.

最好的折衷办法可能是仅在调试应用程序时调用 Console.ReadLine 方法,将其包装在预处理器指令中.类似的东西:

The best compromise is probably to call the Console.ReadLine method only when debugging the application by wrapping it in a preprocessor directive. Something like:

#if DEBUG
    Console.WriteLine("Press enter to close...");
    Console.ReadLine();
#endif

如果抛出未捕获的异常,您可能还希望窗口保持打开状态.为此,您可以将 Console.ReadLine(); 放在 finally 块中:

You might also want the window to stay open if an uncaught exception was thrown. To do that you can put the Console.ReadLine(); in a finally block:

#if DEBUG
    try
    {
        //...
    }
    finally
    {
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
#endif

这篇关于为什么控制台窗口在显示我的输出后立即关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆