C# Simple Event Handler for Setting Alarm

我是研究僧i 提交于 2019-12-11 03:53:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!