时间跨度减去秒表倒计时

Time span subtract stopwatch countdown

我正在使用 WinForm 的。我的表单中有一个标签,应该从 0:20 秒开始倒计时。到 0:00 秒。我在这里尝试这样做,但编译器给我一个错误。

Error: Cannot convert from 'int' to 'System.TimeSpan'

为什么我不能使用 timespan.Subtract()?我如何从 0:20 倒数到 0:00 秒?

    private void timer1_Tick(object sender, EventArgs e)
    {
        TimeSpan timespan = TimeSpan.FromSeconds(20);

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        Time_label.Text = timespan.Subtract(stopwatch.Elapsed.Seconds);
    }

stopwatch.Elapsed.Secondsreturns和int,具体是秒数。 timespan.Subtract(TimeSpan) 接受一个 TimeSpan 对象。

你可以试试:

Time_label.Text = 20 - stopwatch.Elapsed.Seconds;

Time_label.Text = timespan.Subtract(stopwatch.Elapsed).Seconds;

请注意您的逻辑有问题。每次触发 tick 事件时都会重新启动一个新的秒表,因此每次触发时都会有一个新的 0:00 秒表,并且文本框中会显示 19 或 20。 在其他地方实例化您的秒表,使其在刻度之间相同。

编辑: 正如 Quantic 的评论所建议的那样,如果你计划有超过一分钟的时间

Time_label.Text = (int)timespan.Subtract(stopwatch.Elapsed).TotalSeconds;

TimeSpan.Subtract 需要另一个 TimeSpan 结构。 Stopwatch.Elapsed.Seconds 是一个 Int32 结构。没有任何内置的隐式转换可以将 Int32 转换为 TimeSpan。你可以试试这个

Time_label.Text = timespan.Subtract(TimeSpan.FromSeconds(stopwatch.Elapsed.seconds)).ToString();

TimeSpan.Subtract 期望您从中减去另一个 TimeSpan 实例(TimeSpan 本身不受特定时间单位的约束,因此通过减去说“15”它不会 "know" 什么你心目中的单位)。

你想要的是

Time_label.Text = Timespan.Subtract(TimeSpan.FromSeconds(stopwatch.Elapsed.Seconds)));

这会产生一个相当漂亮的预格式化

00:00:20

或者(利用 Stopwatch 的 Elapsed 本身就是一个 TimeSpan 这一事实)

Time_label.Text = timespan.Subtract(stopwatch.Elapsed);

但这会产生

00:00:19.9999765

这可能过于精确,无法向最终用户显示(这是由于秒表精确到滴答声造成的)。

一个简单的第二个计数器更好的方法是利用 Timer 本身。

private readonly Timer _timer;    
private TimeSpan _timespan;
private readonly TimeSpan _oneSecond;

public Form1()
{
    InitializeComponent();

    _timer = new Timer();
    _timer.Tick += timer1_Tick;
    _timer.Interval = 1000;       

    _timespan = TimeSpan.FromSeconds(20);
    _oneSecond = new TimeSpan(0, 0, 0, 1);

    _timer.Start();
}

private void timer1_Tick(object sender, EventArgs eventArgs)
{
    if (_timespan >= TimeSpan.Zero)
    {
        Time_label.Text = _timespan.ToString(@"m\:ss");
        _timespan = _timespan.Subtract(_oneSecond);
    }
    else
    {
        _timer.Stop();
    }
}