问题
Why does the following line "alarm.AlarmEvent += new AlarmEventHandler(alarm_Sound);" gives me "An object reference is required for the non-static field, method, or property 'AlarmClock.Alarm.alarm_Sound(object, System.EventArgs)'"
public static void Main(string[] args)
{
Alarm alarm = new Alarm(new DateTime(2010, 4, 7, 23, 2, 0));
alarm.Set();
alarm.AlarmEvent += new AlarmEventHandler(alarm_Sound);
}
Full source code here: Program.cs AlarmEventArgs
回答1:
You're adding the event handler after calling the Set
method.
Therefore, when the Set
method raises the event, it doesn't have a handler yet.
回答2:
Your alarm_Sound
method is an instance method, meaning that it can only be used on an instance of your class.
Since Main
is a static
method, it is not associated with an instance of the class, so you cannot use any instance methods in it.
You need to make your alarm_Sound
handler method a static method by adding the static
keyword to its declaration.
Alternatively, you could create an instance of the class, then reference the handler method of that instance.
回答3:
Because the alarm_Sound method is defined in the context of the Class named Alarm in the Program.cs file, so, for calling it, you would need a instance of that class.
It would be better to define it as static
so you don't need an instance for calling that method
来源:https://stackoverflow.com/questions/2593988/c-sharp-simple-event-handler-for-setting-alarm