天天看点

C# 编程基础知识 2 - Hello World 探究之一:什么是Console

在我们的Hello,World程序中,我们使用了

Console.WriteLine("Hello,World!");

来显示“Hello, World!”字符串,那么这句代码中的Console到底是什么呢?

MSDN 中介绍Console的原文如下:

The console is an operating system window where users interact with the operating system or a text-based console application by entering text input through the computer keyboard, and reading text output from the computer terminal. For example, in Windows the console is called the command prompt window and accepts MS-DOS commands. The Console class provides basic support for applications that read characters from, and write characters to, the console.

Console I/O Streams

When a console application starts, the operating system automatically associates three I/O streams with the console. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the In, Out, and Error properties.

By default, the value of the In property is a System.IO..::.TextReader object, and the values of the Out and Error properties are System.IO..::.TextWriter objects. However, you can set these properties to streams that do not represent the console; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the SetIn, SetOut, or SetError method, respectively. I/O operations using these streams are synchronized, which means multiple threads can read from, or write to, the streams.

于其中红色的文本所示,对Windows操作系统而言, Console就是那个黑乎乎的Cmd 窗口。不过奇妙的是MSDN讲我们可以重定义Console 的输入流和输出流(However, you can set these properties to streams that do not represent the console; for example, you can set these properties to streams that represent files.) 那就让我们尝一尝吧!

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace HelloWorld01

{

    class Program

    {

        static void Main(string[] args)

        {

            using (System.IO.TextWriter streamWriter = new System.IO.StreamWriter(@”C:/ConsoleOutput.txt”))

            {

                Console.SetOut(streamWriter);

                Console.WriteLine(”Hello, World!”);

            }

        }

    }

在上端代码中,我们调用

Console.SetOut(streamWriter);

把Console的输出重定义成C盘下的ConsoleOutput.txt. 那么我们究竟能不能在运行上面的程序后,在那个文件里看到"Hello, World!"呢?

何不运行一下看看?

本文英文版本及Visual Studio工程文件可以参看此处。