【问题标题】:C# class instance specfic timer elapsed eventC# 类实例特定计时器经过事件
【发布时间】:2017-01-03 17:49:49
【问题描述】:

在我的程序中,我需要生成一个名为“Vehicle”的类的实例,当计时器达到一个间隔时,Vehicle 类中有一个计时器,以及一个布尔值“vExists”。

class VehicalGen
{
    private Random rn1 = new Random();

    private int agrotime;
    private bool vExists;
    //static AgrivationHandler agroTimeHandler;
    private static Timer agroTimer = new Timer(100);

    //agrotime: anywhere between 2 and 4 seconds (2000 to 4000)

    ///Generates the new Vehicles using GetCarType to change the outcome of the later variables
    public VehicalGen()
    {
        this.vtype = RandomGeneration.GetCarType(rn1);
        switch (this.vtype)
        {
            [....] //This is where the details of the vehicle are generated.
        }
        this.agrotime = RandomGeneration.GetRandomTime224(rn1);
        this.vExists = true;
        this.serviced = false;
        //agroTimeHandler = new AgrivationHandler(agrotime);
        agroTimer.Interval = agrotime;
        agroTimer.Elapsed += AgroTimerElapsed;
        agroTimer.Start();
    }

    public static void AgroTimerElapsed(object sender, ElapsedEventArgs e)
    {
        //here is where I need to set vExists to "False"
    }
}

但是,据我所知,我需要生成该类的特定实例,因为它不喜欢“this.vExists = false”,它只是错误。

【问题讨论】:

  • 您应该尝试编写代码并将其发布在此处(有关指导,请参阅minimal reproducible example)。尝试其他任何事情(跳跃、唱歌、跑步)都无济于事,而且绝对不会发布好的 SO 问题。

标签: c# timer


【解决方案1】:

是的,是可能的。 请尝试以下操作:

private void LoadTimer()
   Timer timer = new Timer
   timer.Interval = 4000;
   timer.Enabled = true; 
   timer.Tick += new EventHandler(timer1_Tick);
   timer.Start(); 
}

private void timer1_Tick(object sender, EventArgs e)
{
   // do your boolean operation where
}

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多