以下是《C#之钥编程》一书中的一个小时钟程序。我根本不熟悉 Timers 库,所以我不太了解其中的一些语法。我想了解但不了解的是这个小程序的方法中的 Console.Write(str) 行。 Main 如何知道将什么打印到控制台?是空的 Console.WriteLine() 调用让时间每秒打印一次吗?当我阅读这些概念时,事后似乎很容易理解发生了什么。根据我的提问,关于 C# 的哪些方面我还没有真正理解?
using System;
using System.Timers; // Requires System.dll
class Clock
{
static int iStringLength;
static void Main()
{
Console.WriteLine("Press Enter to end program");
Console.WriteLine();
Timer tmr = new Timer();
tmr.Elapsed += new ElapsedEventHandler(TimerHandler);
tmr.Interval = 1000;
tmr.Start();
Console.ReadLine();
tmr.Stop();
}
static void TimerHandler(object obj, ElapsedEventArgs eea)
{
Console.Write(new String('\b', iStringLength));
string str = String.Format("{0} {1} ",
eea.SignalTime.ToLongDateString(),
eea.SignalTime.ToLongTimeString());
iStringLength = str.Length;
Console.Write(str);
}
}
请您参考如下方法:
Main() 不会向控制台打印任何内容,除了最初的空白行。
TimerHandler() 回调中的
Console.Write() 每秒运行一次并打印时间。
