问题描述
我有一个计时器,我想放置计时器回调但是,我得到了这个错误.
I have a timer and I want to put timer callbacks into separate functions, however, I get this error.
需要对象引用才能访问非静态字段、方法或属性''...
An object reference is required to access non-static field, method, or property ''...
如果我将这些回调声明为委托事件并且成员变量作为静态的,它工作正常.我应该这样吗?
If I declare these callbacks as delegate events and member variables as static, it works fine. Should I leave it that way?
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();
}
}
推荐答案
这取决于你想要做什么.您可以或者将事物设为静态,或者您可以创建一个实例:
It depends what you're trying to do. You can either make things static, or you can create an instance:
MainClass instance = new MainClass();
btn.Clicked += instance.StartClick;
btn_stop.Clicked += instance.StopClick;
我认为这不是您的真实应用程序,因此很难说您应该在真实代码中做什么.就个人而言,我倾向于创建一个实例 - 静态变量代表全局状态,这通常是一个坏主意(就可测试性等而言).不过,我们无法确定这是否会影响您的情况.
I assume this isn't your real application, so it's hard to say what you should do in your real code. Personally I'd lean towards creating an instance - static variables represent global state which is usually a bad idea (in terms of testability etc). We can't tell whether that affects your situation or not though.
重要的是您了解为什么您会收到错误消息以及为什么上述更改可以修复它.一旦您了解了这一点,您将能够更好地做出最佳决策.
What's important is that you understand why you're getting the error message and why the above change fixes it. Once you understand that, you'll be in a better situation to make the best decisions.
这篇关于访问非静态成员需要对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!