在 C# 中通过委托实现观察者模式?
已经回答了一个问题 在 C# 中,是观察者模式不是已经使用事件实现了吗?
它询问观察者模式是否已经在 C# 中使用事件实现。
当我获得事件和观察者模式时,观察者模式是否真的只是委托,而事件是进一步的实现?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的。 事件只是一个具有一些略有不同功能的委托。 所有观察者模式都可以使用委托来实现,而无需触及
event
关键字。那么您可能会对“event”关键字实际带来什么感兴趣。
常规委托字段不能
但常规委托可以为
:这里有一篇很棒的文章,其中对事件和委托之间的 IL 代码进行了比较。 (提示:几乎是一样的)。
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.
regular delegate field cannot
but regular delegates can
Edit: Here's a great writeup with IL code comparison between events and delegates. (Hint: it's pretty much the same).