Events - naming convention and style

后端 未结 7 678
北海茫月
北海茫月 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 10:57

    In your case it could be:

    class Metronome {
      event Action Ticked;
    
      internalMethod() {
        // bla bla
        Ticked();
      }
    }
    

    Above sampple use below convention, self-describing ;]

    Events source:

    class Door {
    
      // case1: property change, pattern: xxxChanged
      public event Action LockStateChanged;
    
      // case2: pure action, pattern: "past verb"
      public event Action Opened;
    
      internalMethodGeneratingEvents() {
        // bla bla ...
    
        Opened(true);
        LockStateChanged(false);
      }
    
    }
    

    BTW. keyword event is optional but enables distinguishing 'events' from 'callbacks'

    Events listener:

    class AlarmManager {
    
      // pattern: NotifyXxx
      public NotifyLockStateChanged(bool state) {
        // ...
      }
    
      // pattern: [as above]      
      public NotifyOpened(bool opened) {
      // OR
      public NotifyDoorOpened(bool opened) {
        // ...
      }
    
    }
    

    And binding [code looks human friendly]

    door.LockStateChanged += alarmManager.NotifyLockStateChanged;
    door.Moved += alarmManager.NotifyDoorOpened;
    

    Even manually sending events is "human readable".

    alarmManager.NotifyDoorOpened(true);
    

    Sometimes more expressive can be "verb + ing"

    dataGenerator.DataWaiting += dataGenerator.NotifyDataWaiting;
    

    Whichever convention you choose, be consistent with it.

提交回复
热议问题