我正在按照 MSDN 中的指南学习 C#。
现在,我刚刚尝试了示例 1(here 是 MSDN 的链接),我遇到了一个问题:为什么控制台窗口关闭立即显示我的输出?
using System;
public class Hello1
{
public static int Main()
{
Console.WriteLine("Hello, World!");
return 0;
}
}
最佳答案
the issue here is that their Hello World Program is showing up then it would immediately close.
why is that?
因为它已经完成了。当控制台应用程序完成执行并从它们的 main
方法返回时,相关的控制台窗口会自动关闭。这是预期的行为。
如果您想让它保持打开状态以进行调试,您需要指示计算机在结束应用并关闭窗口之前等待按键。
Console.ReadLine
method是这样做的一种方式。将此行添加到代码末尾(就在 return
语句之前)将导致应用程序在退出前等待您按下某个键。
或者,您可以在 Visual Studio 环境中按 Ctrl+F5 启动应用程序而不附加调试器,但这有一个明显的缺点,即阻止您使用调试功能,您在编写应用程序时可能希望使用这些功能。
最好的折衷方案可能是仅在调试应用程序时调用 Console.ReadLine
方法,方法是将应用程序包装在预处理器指令中。像这样的东西:
#if DEBUG
Console.WriteLine("Press enter to close...");
Console.ReadLine();
#endif
如果抛出未捕获的异常,您可能还希望窗口保持打开状态。为此,您可以将 Console.ReadLine();
放在 finally
block 中:
#if DEBUG
try
{
//...
}
finally
{
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
#endif
关于c# - 为什么控制台窗口在显示我的输出后立即关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868338/