When invoking the timer callbacks in separate functions, one may encounter the error "An object reference is required to access non-static field, method, or property..." This arises when accessing non-static class members within static methods or events.
To resolve this, there are two options:
Declare Callbacks and Member Variables as Static:
public static void Main (string[] args) { Timer _timer = null; static TimeSpan _millisecs; ... }
Create an Instance of the Class:
MainClass instance = new MainClass(); btn.Clicked += instance.StartClick; btn_stop.Clicked += instance.StopClick;
The choice between these options depends on the application's requirements. If global state management is preferred, static members can be used. Alternatively, creating an instance provides better testability and encapsulation.
Understanding the error message's cause helps make informed decisions. The error occurs because non-static members require an object instance to be accessed, whereas static members do not.
The above is the detailed content of How to Resolve 'An Object Reference is Required' Error When Accessing Non-Static Members in C#?. For more information, please follow other related articles on the PHP Chinese website!