控制台输出问题,C#

时间:2015-04-16 18:02:09

标签: c#

我正在学习用C#编程,而且我在控制台上遇到问题,当我在控制台下方运行代码时显示输出但是立即关闭窗口我看不到任何东西。我不知道如何保持窗户打开。有什么建议吗?我将非常感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testApp_1
{
    class Program
    {
        static void Main(string[] args)
        {
            String word = "Hello world!";

            Console.WriteLine(word);
        }
    }
}

6 个答案:

答案 0 :(得分:2)

这是因为当您到达最后一行时,您也会到达程序的末尾,因此它会终止。要保持控制台窗口打开,只需添加即可 Console.ReadKey()作为最后一行。

答案 1 :(得分:2)

写入控制台后继续执行,然后程序退出。你需要做一些事情来暂停执行,通常你会从控制台读取一些东西:

Console.ReadKey(); 

暂停直到用户按下某个键

所以你的整个程序可能如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testApp_1
{
    class Program
    {
        static void Main(string[] args)
        {
            String word = "Hello world!";

            Console.WriteLine(word);

            //if you want the user to exit with any key press do this
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

            //if you want the user to hit 'enter' to exit do this
            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }
}

您可以在MSDN上阅读Console.ReadKeyConsole.ReadLine

答案 2 :(得分:1)

您的代码会立即关闭,因为它没有其他任何事情可做。您要做的是将其添加到代码的底部:

Console.Readline();

这将导致它等到你按Enter键。

答案 3 :(得分:0)

如果你按ctrl + F5(没有调试运行)它将不会关闭。但是如果你运行调试,它将在执行后关闭。 您可以在最后使用Console.ReadLine();等待用户点击返回。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testApp_1
{
    class Program
    {
        static void Main(string[] args)
        {
            String word = "Hello world!";

            Console.WriteLine(word);
            Console.ReadLine();
        }
    }
}

答案 4 :(得分:0)

您可以使用以下方法来阅读一些用户输入: https://msdn.microsoft.com/de-de/library/system.console.readline%28v=vs.110%29.aspx

但你必须做一些输入。

您还可以使用记录器框架:log4net: http://logging.apache.org/log4net/

答案 5 :(得分:0)

缺少Console.ReadLine()。