c# .net2.0 - 让我展示一个关于将方法作为参数传递的主题的详细答案。在我的场景中,我正在配置一组具有不同_Tick方法的System.Timers.Timer。
delegate void MyAction();
Timer tmr1, tmr2, tmr3;
int tmr1_interval = 4.2,
tmr2_interval = 3.5;
tmr3_interval = 1;
public MyClass()
{
..
ConfigTimer(tmr1, tmr1_interval, this.Tmr_Tick);
ConfigTimer(tmr2, tmr2_interval, (sndr,ev) => { SecondTimer_Tick(sndr,ev); });
ConfigTimer(tmr3, tmr3_interval, new MyAction((sndr,ev) => { Tmr_Tick((sndr,ev); }));
..
}
private void ConfigTimer(Timer _tmr, int _interval, MyAction mymethod)
{
_tmr = new Timer() { Interval = _interval * 1000 };
_tmr.Elpased += (sndr, ev) => { mymethod(sndr, ev); };
_tmr.Start();
}
private void Tmr_Tick(object sender, ElapsedEventArgs e)
{
((Timer)sender).Stop();
((Timer)sender).Start();
}
private void SecondTimer_Tick(object sender, ElapsedEventArgs e) {..}