所以我尝试在我的代码中添加一个计时器,每 1.5 秒我的 vehCount 就会增加 1。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace AssignmentCA
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Vehicle.vehCount);
Console.ReadLine();
}
class Vehicle
{
public static int vehCount = 0;
private void spawnVehicle()
{
Timer tm = new Timer();
tm.Interval = 1500;
tm.Elapsed += timerTick;
vehCount++;
tm.Start();
}
private void timerTick(object sender, EventArgs e)
{
vehCount++;
}
}
}
}
在我运行之前和运行时从未使用过计时器,我得到 0,但它从不递增 1。我怎样才能实现这一目标。
最佳答案
我不是很清楚你想做什么,但你根本没有调用 spawnVehicle 方法。
这是针对您发布的内容的解决方案。看 spawnVehicle 是在 Vehicle 类的静态构造函数上调用的!为了从静态构造函数调用 spawnVehicle,它也需要是静态的。
class Vehicle
{
static Vehicle()
{
spawnVehicle();
}
public static int vehCount = 0;
static void spawnVehicle()
{
Timer tm = new Timer();
tm.Interval = 1500;
tm.Elapsed += (s, e) => vehCount++;
vehCount++;
tm.Start();
}
}
关于c# - 定时器控制增量计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612527/