List:自定义对象如何从列表中删除自身?
我创建了一个类,它实现了带有 elapse 事件的 System.Timers.Timer 。
private void ElapseEvent(object source, ElapsedEventArgs e){
//read from serial port device
}
在主程序中,我有一个 private List
。
我动态启动计时器并将其添加到计时器列表中。
var timer1= new MyTimerClass();
timer1.Execute("Device A");
_timers.Add(timer1);
var timer2= new MyTimerClass();
timer2.Execute("Device B");
_timers.Add(timer2);
当ElapseEvent
遇到错误并且串口断开连接时,我想从列表中删除计时器。我怎么可能这么做呢?
I created a class that implements a System.Timers.Timer
with an elapse event.
private void ElapseEvent(object source, ElapsedEventArgs e){
//read from serial port device
}
In the main program I have a private List<MyTimerClass> _timers
.
I dynamically start the timer and add it to the timer list.
var timer1= new MyTimerClass();
timer1.Execute("Device A");
_timers.Add(timer1);
var timer2= new MyTimerClass();
timer2.Execute("Device B");
_timers.Add(timer2);
When the ElapseEvent
encounters an error and the serial port was disconnected, I want to remove the timer from the List. How can I possibly do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在包含计时器的类中添加 OnError 方法。为了让父类知道发生了错误。类似于以下内容:
在 MyTimerClass
在父类中:
You can add a OnError Method at the class that contains the timers. In order to let the parent class know that an error occurs. Something like the following:
At MyTimerClass
At the parent class:
如果您的 _timers 是静态变量,则在同一类中创建静态事件处理程序。当计时器的
ElapseEvent
中引发错误时,调用引用其自身的事件处理程序,并让静态事件处理程序从列表中删除出错的计时器。If your _timers is a static variable, then create a static event handler in the same class. When the error is thrown in a timer's
ElapseEvent
, call the event handler with reference to itself, and have the static event handler remove the error'ed timer from the list.观察者模式。 .NET 对此有本机支持。
The Observer Pattern. .NET has native support for this.
您应该查看命令模式;听起来这对你来说是完美的。
You should check out the Command Pattern; sounds like it would be perfect for you.