Observer pattern implemented in C# with delegates?

点点圈 提交于 2019-12-20 09:59:39

问题


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 implemented in c# using events.

While I get the events and observer pattern, isn't the observer pattern really just delegates and events is a further implementation?


回答1:


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).



来源:https://stackoverflow.com/questions/1023329/observer-pattern-implemented-in-c-sharp-with-delegates

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