如何使TimeSpan在几秒钟内开始滴答作响?

时间:2018-04-18 03:19:53

标签: c# datetime timespan

如何让我的TimeSpan对象在几秒钟内打勾?

private TimeSpan time;

public Clock{
    time = new Timespan(0, 0, 0);
}

public void Tick()
{
   //start ticking in seconds
}

1 个答案:

答案 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