什么时候使用回调而不是c#中的事件? [英] When to use callbacks instead of events in c#?

查看:114
本文介绍了什么时候使用回调而不是c#中的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我,如果这是一个愚蠢的问题,我承认我没有想过太多。



但是你什么时候会喜欢使用回调(即传递一个Func或Action),而不是暴露和使用一个事件?



更新



这个问题是什么促成了以下问题:


我有一个ThingsHandler类,其中
可以与ThingEditor。
The ThingsHandler处理一个
的列表事情,知道他们的顺序,哪一个是'当前',新的
添加或删除等。



ThingEditors可以修改单个
的东西。



当用户选择
a new Thing进行编辑时,ThingsHandler需要警告
ThingEditor,而
ThingEditor需要提醒
ThingsHandler当用户说
'done'。


令我困扰的是让这两个类持有引用相互之间 - 虽然我猜这是不可避免的 - 或者是束缚双方的事件。我想知道在一个方向使用回调是否清洁。



我怀疑有这样的设计模式,对我的无知(和怠惰)谦虚道歉。

解决方案

我在几种情况下使用回调,我知道只会 一次,回调是特定于单个方法调用(而不是对象实例)的特定 - 例如,作为异步方法的返回部分。



静态实用程序方法尤其如此(因为没有一个实例,静态事件在不小心使用时会被致命而且被避免),但是另一个选项是创建一个带事件的类实例


Forgive me if this a stupid question, I admit I haven't thought about it much.

But when would you favour using a callback (i.e, passing in a Func or Action), as opposed to exposing and using an event?

UPDATE

What motivated this question was the following problem:

I have a ThingsHandler class, which can be associated with a ThingEditor. The ThingsHandler handles a list of Things, knows their order, which one is 'current', when new ones are added or deleted etc.

The ThingEditors can just modify a single thing.

The ThingsHandler needs to alert the ThingEditor when the user selects a new Thing to edit, and the ThingEditor needs to alert the ThingsHandler when the user says 'done'.

What bothers me is having these two classes holding references to each other - though I guess that's inevitable - or binding to events in both directions. I wondered if using a callback in one direction was 'cleaner'.

I suspect there is a design pattern for this, and humbly apologise for my ignorance (and sloth).

解决方案

I use callbacks in a few cases where I know it will only ever fire once, and the callback is specific to a single method call (rather than to an object instance) - for example, as the return part of an async method.

This is particularly true of static utility methods (since you don't have an instance, and static events are deadly when used carelessly, and to be avoided), but of course the other option is to create a class instance with an event instead.

这篇关于什么时候使用回调而不是c#中的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆