我正在使用 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);
}
最佳答案
一个简单的秒计数器的更好方法是使用 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();
}
}
关于c# - 时间跨度减去秒表倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473726/