为什么事件在.NET没有返回类型? [英] Why events have no return types in .NET?

查看:154
本文介绍了为什么事件在.NET没有返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事件还'不'类似方法,但他们没有返回类型,只是空洞?

Events also 'does' something like methods, but they don't have return types and just voids?

我很想知道,为什么会这样呢?而他们为什么不返回值的类型?

I am curious to know, Why is it so? and Why don't they return types?

推荐答案

由于事件可以由多个监听器来处理。还有就是不能保证为事件处理程序(虽然我认为他们在他们订阅在现实中的顺序是所谓的。)

Because events can be handled by multiple listeners. There is not guaranteed order to the event handlers (though I think they're called in the order they are subscribed in reality.)

相反,对于那些希望回归的一些数据事件,该公约是有一个可变EventArgs对象,如CancelEventArgs它可以有它的取消属性设置为true。这在一个返回值的优点是链的事件处理程序可以看看属性,看看其他处理程序已经设置。但你还是风的情况是,最后一个设置属性的胜利。

Instead, for events that want to "return" some data, the convention is to have a mutable EventArgs object such as CancelEventArgs which can have its Cancel property set to true. The advantage of this over a return value is that event handlers in the chain can look at the property to see if another handler already set it. But you still wind up with a situation where the last one to set the property wins.

如果它是一个返回值,整个概念将是一个复杂多了。

If it were a return value, the whole concept would be a lot more complicated.

这篇关于为什么事件在.NET没有返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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