2017-01-03 68 views
-3

在我的程序中,我需要生成一個類爲「Vehicle」的實例,Vehicle類中有一個定時器,以及一個布爾型「vExists」,當定時器命中間隔。C#class instance specfic timer elapsed event

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 =假」,它只是錯誤。

+0

您應該嘗試編寫代碼並將其發佈到此處(請參閱[MCVE]以獲取指導)。嘗試其他任何事情(跳躍,唱歌,跑步)都不會幫助,並且絕對不會讓事情變得如此糟糕。 –

回答

0

是可以的。 請嘗試以下操作:

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 
} 
相關問題