gpt4 book ai didi

c# - 永不结束 while 循环

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:44 25 4
gpt4 key购买 nike

这是一本 C# 书中的示例:

//  Timer02.cs - Displaying Date and Time
// Using the Timer class.
// Press Ctrl+C or 'q' folllwed by Enter to end program.
//------------------------------------------------------------
using System;
using System.Timers;

class myApp
{
public static void Main()
{
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000;
myTimer.Start();


while (Console.Read() != 'q')
{
; // do nothing...
}
}

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
Console.Write("\r{0}", DateTime.Now);
}
}

我猜想循环会一直运行到 q 被按下,但是当 q 被按下时循环并没有结束。

我在这里缺少什么?

最佳答案

我怀疑你没有在 q 之后按回车键。 Console.Read方法会阻塞,直到有一整行要读取,即使它实际上只读取该行的单个字符。

来自文档:

The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

关于c# - 永不结束 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16197792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com