定时器控制增量计数器

时间:2017-04-25 13:47:50

标签: c# timer

所以我试图在我的代码中添加一个计时器,每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.我怎样才能实现这一点。

1 个答案:

答案 0 :(得分:3)

我不清楚你想做什么,但你根本就没有调用spawnVehicle方法。

这是您发布的解决方案。看看在类Vehicle的静态构造函数上调用spawnVehicle!为了从静态构造函数调用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();
    }
}
相关问题