我正在制作一个 WPF 应用程序来模拟流量。我希望汽车在改变加速度之前有 1 秒的 react 延迟,而不停止整个应用程序。为此,我想从我的 Car
类访问 elapsed
变量。 elapsed
变量存储已经过去的时间。
MainWindow
中的代码:
namespace TrafficTester
{
public partial class MainWindow : Window
{
Timer timer = new Timer();
public MainWindow()
{
InitializeComponent();
//create the timer
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = timerInterval;
timer.Enabled = true;
//...
void OnTimedEvent(object source, ElapsedEventArgs e)
{
timer.Enabled = false; //stop timer whilst updating, so updating won't be called again before it's finished
update(); //
timer.Enabled = true;
elapsed += timerInterval;
}
}
}
Car
类中的代码:
namespace TrafficTester
{
public class Car
{
//...
public void changeAccel(double val)
{
int time = MainWindow.elapsed;
int stop = MainWindow.elapsed + reactDelay;
while (time < stop)
{
time = MainWindow.elapsed;
}
accel = val;
}
}
}
accel
是当前加速度,val
是新加速度。 MainWindow.elapsed
应该从 MainWindow 调用 elapsed
变量,但事实并非如此。如何从 Car
类中调用它?
最佳答案
我至少看到了两个问题:
- 如果你想访问定时器实例,它需要是公共(public)的。
- 然后您可以通过主窗口的实例访问它。
要获取耗时,就像您可能想要的那样,您需要从 ElapsedEventHandler 开始并在那里执行计时操作!
public partial class MainWindow : Window
{
public System.Timers.Timer myTimer = new System.Timers.Timer();
public MainWindow()
{
//create the timer
myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Where is it?
myTimer.Interval = 5;
myTimer.Enabled = true;
}
//...
void OnTimedEvent(object source, ElapsedEventArgs e)
{
myTimer.Enabled = false; //stop timer whilst updating, so updating won't be called again before it's finished
//update(); //
myTimer.Enabled = true;
// Timer.Elapsed += 5;
}
}
public class Car
{
public void changeAccel(double val)
{
var myWin = (MainWindow)Application.Current.MainWindow;
int time = myWin.myTimer.Elapsed; //<-- you cannot use it this way
}
}
关于c# - 从类访问 MainWindow 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746088/