当前位置: 移动技术网 > IT编程>开发语言>c# > C#基于TimeSpan实现倒计时效果的方法

C#基于TimeSpan实现倒计时效果的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例展示了c#基于timespan实现倒计时效果的方法,比较实用的功能,对于初学者来说有一定的学习参考价值。具体实现方法如下:

示例代码如下:

using system;
using system.threading;

namespace consoleapplication29
{
  class program
  {
    static void main(string[] args)
    {
      try
      {
        datetime _timeend = datetime.now.addseconds(62);
        threadpool.queueuserworkitem((arg) =>
        {
          timespan _ts = _timeend - datetime.now;
          while (true)
          {
            thread.sleep(1000);
            if (_ts.totalseconds >= 0)
            {
              console.writeline("还剩余{0}分钟{1}秒", _ts.minutes, _ts.seconds);
              _ts = _ts.addseconds(-1);
            }
          }
        });
      }
      catch (exception ex)
      {
        console.writeline(ex.message);
      }
      finally
      {
        console.readline();
      }
    }
  }
  public static class timespantoolv2
  {
    public static timespan addseconds(this timespan ts, int seconds)
    {
      return ts.add(new timespan(0, 0, seconds));
    }
    public static timespan addminutes(this timespan ts, int minutes)
    {
      return ts.add(new timespan(0, minutes, 0));
    }
    public static timespan addhours(this timespan ts, int hours)
    {
      return ts.add(new timespan(hours, 0, 0));
    }
  }
}

代码运行效果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网