定时器控制增量计数器
问题描述:
所以我试图在我的代码中加入一个定时器,在每1.5秒我的vehCount将增加一个。定时器控制增量计数器
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();
}
}
+1
通过访问vehCount,构造函数被自动调用 – user1845593
+0
输出到控制台将很高兴看它是否工作。 – Ryan
你的'spawnVehicle'方法没有被调用 - 定时器不被创建 – Ryan
是车辆意味着一个静态类吗? – Orangesandlemons
使你的方法公开和静态 - 然后在Main中调用。 – Ryan