我有一个计时器,我想将计时器回调放入单独的函数中,但是,出现此错误。
需要对象引用才能访问非静态字段,方法或属性''...
如果我将这些回调声明为委托事件,并将成员变量声明为静态,则可以正常工作。我应该这样吗?
class MainClass
{
private Timer _timer = null;
private TimeSpan _millisecs;
public static void Main (string[] args)
{
Application.Init();
MainWindow win = new MainWindow();
Label lbl = new Label();
lbl.Text = "00:00";
Table tbl = new Table(2, 2, true);
tbl.Name = "tbl";
Button btn = new Button("Start");
tbl.Attach(lbl, 0, 2, 0, 1);
tbl.Attach(btn, 0, 1, 1, 2);
Button btn_stop = new Button("Stop");
tbl.Attach(btn_stop, 1, 2, 1, 2);
btn.Clicked += StartClick;
btn_stop.Clicked += StopClick;
win.Add(tbl);
win.ShowAll();
Application.Run ();
}
private void StartClick(object obj, EventArgs args)
{
if (_timer == null) {
_timer = new Timer();
_timer.Elapsed += delegate(object sender, ElapsedEventArgs e) {
_millisecs = _millisecs.Add(new TimeSpan(0, 0, 0, 0, 50));
lbl.Text = new DateTime(_millisecs.Ticks).ToString("ss:ff");
};
_timer.Interval = 50;
_timer.Enabled = true;
}
_timer.Start();
}
private void StopClick(object obj, EventArgs args)
{
_timer.Stop();
}
}
斯蒂芬大帝
犯罪嫌疑人X
相关分类