Observer pattern implemented in C# with delegates?

后端 未结 1 1935
心在旅途
心在旅途 2021-02-03 10:48

There is a question already answered which is In C#, isn't the observer pattern already implemented using Events?

It asks if the observer pattern is already implemen

1条回答
  •  孤城傲影
    2021-02-03 11:49

    You are correct. An event is simply a delegate with some slightly different functionality. All of the observer pattern can be implemented with delegates without ever touching the event keyword.

    You may be interested then, in what the "event" keyword actually brings to the table.

    • Events can be part of an interface, whereas regular delegate field cannot
    • Events cannot be invoked by outside classes, but regular delegates can
    • Events have additional accessors (add and remove) that you can override and provide custom functionality for

    Edit: Here's a great writeup with IL code comparison between events and delegates. (Hint: it's pretty much the same).

    0 讨论(0)
提交回复
热议问题