這是我在 C# 中模擬數字時鐘的代碼。這個對嗎?
如何優化此代碼?這段代碼會消耗大量記憶體嗎?您建議的解決方案是什么?
namespace clock
{
class Program
{
static void Main(string[] args)
{
int h=0, m=0, s = 0;
for (; s<=60; s )
{
Console.WriteLine(string.Format("{0}:{1}:{2}",h,m,s));
// Thread.Sleep(10);
if (s == 59) {
if (m == 59) {
if (h == 24) {
h = 0;
m = 0;
s = 0;
}
h ;
m = 0;
s = 0;
}
m ;
s = 0;
}
}
Console.ReadKey();
}
}
}
uj5u.com熱心網友回復:
有一個System.Timers.Timer類,你可以參考這個解釋它的鏈接(見示例部分):https :
//docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net- 6.0
uj5u.com熱心網友回復:
最好使用System.Threading.Timer Class ,查看鏈接 https://docs.microsoft.com/en-us/dotnet/standard/threading/timers
uj5u.com熱心網友回復:
您需要使用Timer類。有關更多資訊,請查看以下帖子: C# 中的實時時鐘
uj5u.com熱心網友回復:
您可以使用新的 PeriodicTimer
async Task Main()
{
var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
int h = 0, m = 0, s = 0;
while (await timer.WaitForNextTickAsync())
{
Console.WriteLine(string.Format("{0}:{1}:{2}", h, m, s));
if (s == 59)
{
if (m == 59)
{
if (h == 24)
{
h = 0;
m = 0;
s = 0;
}
h ;
m = 0;
s = 0;
}
m ;
s = 0;
}
s ;
if (s > 60) { break; }
}
Console.Read();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/395355.html
