简体   繁体   English

使用委托在C#中实现的观察者模式?

[英]Observer pattern implemented in C# with delegates?

There is a question already answered which is In C#, isn't the observer pattern already implemented using Events? 有一个问题已经回答是在C#中,是不是已经使用事件实现的观察者模式?

It asks if the observer pattern is already implemented in c# using events. 它询问观察者模式是否已在c#中使用事件实现。

While I get the events and observer pattern, isn't the observer pattern really just delegates and events is a further implementation? 虽然我得到了事件和观察者模式,但不是观察者模式真的只是委托和事件是进一步的实现吗?

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. 所有观察者模式都可以通过代理实现,而无需触及event关键字。

You may be interested then, in what the "event" keyword actually brings to the table. 您可能会对“event”关键字实际带给表的内容感兴趣。

  • 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. 编辑: 这是一个很棒的写作 ,在事件和代理之间进行IL代码比较。 (Hint: it's pretty much the same). (提示:它几乎一样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM