我如何让 TimeSpan 在几秒钟内开始计时?
How do i make TimeSpan start ticking in seconds?
如何让我的 TimeSpan 对象在几秒钟内滴答作响?
private TimeSpan time;
public Clock{
time = new Timespan(0, 0, 0);
}
public void Tick()
{
//start ticking in seconds
}
A TimeSpan
是一种用于存储时间的数据类型。但是,如果您想要 run/update 间隔一段时间,则需要 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
class.
的更多信息,请参阅 MSDN 中的 this article
如何让我的 TimeSpan 对象在几秒钟内滴答作响?
private TimeSpan time;
public Clock{
time = new Timespan(0, 0, 0);
}
public void Tick()
{
//start ticking in seconds
}
A TimeSpan
是一种用于存储时间的数据类型。但是,如果您想要 run/update 间隔一段时间,则需要 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
class.