简体   繁体   English

为什么Read()不按预期工作?

[英]Why Doesn't Read() work as Expected?

I'm using Visual Studio 2008 for C#. 我正在使用Visual Studio 2008 for C#。 I can't understand why this simple code does not work as expected. 我无法理解为什么这个简单的代码不能按预期工作。 Any ideas? 有任何想法吗? Thanks! 谢谢!

using System;

namespace TryRead
{
    class Program
    {
        static void Main()
        {
            int aNumber;
            Console.Write("Enter a single character: ");
            aNumber = Console.Read(); **//Program waits for [Enter] key. Why?**
            Console.WriteLine("The value of the character entered: " + aNumber);
            Console.Read(); **//Program does not wait for a key press. Why?**
        }
    }
}

//Program waits for [Enter] key. //程序等待[Enter]键。 Why? 为什么?

The Read method blocks its return while you type input characters; 当您键入输入字符时,Read方法会阻止其返回; it terminates when you press the Enter key. 按Enter键时它会终止。 Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). 按Enter键会将与平台相关的行终止序列附加到输入中(例如,Windows附加回车换行符序列)。

//Program does not wait for a key press. //程序不等待按键。 Why? 为什么?

Subsequent calls to the Read method retrieve your input one character at a time [without blocking]. 对Read方法的后续调用一次检索输入的一个字符[不阻塞]。 After the final character is retrieved, Read blocks its return again and the cycle repeats. 检索到最后一个字符后,Read再次阻止其返回并重复循环。

http://msdn.microsoft.com/en-us/library/system.console.read.aspx http://msdn.microsoft.com/en-us/library/system.console.read.aspx

您需要使用Console.ReadKey()而不是Console.Read()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM