C# 控制台程序,定义一个时钟类,包含 :时,分,秒, 3个字段,要求能够设置时间,显示时间,时间能够走

2024-11-01 23:37:07
有1个网友回答
网友(1):

using System;
using System.Timers;

namespace ConsoleApp
{
public class Clock
{
private Timer timer;

private int hour;
private int minute;
private int second;

public Clock()
{
timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}

public void Start()
{
timer.Start();
}

public void Stop()
{
timer.Stop();
}

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
DateTime time = e.SignalTime;

hour = time.Hour;
minute = time.Minute;
second = time.Second;

string display = string.Format("{0}:{1}:{2}",
hour, minute, second);
Console.Clear();
Console.WriteLine(display);
}
}
}

Main函数里写new Clock().Start();
即可。