An object reference is required to access non-stat

2019-01-03 07:22发布

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();          
    }

}

标签: c# mono
2条回答
ゆ 、 Hurt°
2楼-- · 2019-01-03 07:35

It's because you are accessing non-static methods from the static in this case.

Either create object of the class and than call the method

ObjectOfClass obj = new ObjectOfClass();
obj.MethodName();

so in your case

MainClass obj = new MainClass();
btn.Clicked += obj.StartClick;
btn_stop.Clicked += obj.StopClick;

Or create the called methods as static (which you already tried as you said).

查看更多
在下西门庆
3楼-- · 2019-01-03 07:52

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.

查看更多
登录 后发表回答