如何让我的TimeSpan对象在几秒钟内打勾?
private TimeSpan time;
public Clock{
time = new Timespan(0, 0, 0);
}
public void Tick()
{
//start ticking in seconds
}
答案 0 :(得分:2)
TimeSpan
是用于存储时间的数据类型。但是,如果您希望某个时间间隔运行/更新,则需要Timer
。你可以这样实现Timer
:
using System;
using System.Timers;
public class Clock
{
private static Timer aTimer;
private TimeSpan time;
public Clock()
{
// Initialize the time to zero.
time = TimeSpan.Zero;
// Create a timer and set a one-second interval.
aTimer = new System.Timers.Timer();
aTimer.Interval = 1000;
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
// Start the timer.
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
time = time.Add(TimeSpan.FromSeconds(1));
}
}
然后,每当您创建一个new Clock()
对象时,它将获得自己的time
并每秒更新一次。
有关Timer
类的详细信息,请参阅MSDN中的this article。