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工程文件可以参看此处

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值