Events - naming convention and style

后端 未结 7 705
北海茫月
北海茫月 2020-12-02 10:40

I\'m learning about Events / Delegates in C#. Could I ask your opinion on the naming/coding style I\'ve chosen (taken from the Head First C# book)?

Am teaching a fr

7条回答
  •  囚心锁ツ
    2020-12-02 11:00

    A point I have found after using events in .Net for many years is the repetitive need to check the event for a null handler on every invocation. I'm yet to see a piece of live code that does anything but not call the event if it is null.

    What I have started doing is to put a dummy handler on every event I create to save the need to do the null check.

    public class Metronome
    {
        public event EventHandler Tick =+ (s,e) => {};
    
        protected virtual void OnTick(EventArgs e)
        {
            Tick(this, e);  // now it's safe to call without the null check.
        }
    }
    

提交回复
热议问题