事件是不是田 - 我不明白这一点 [英] Events aren't fields - I don't get it

查看:144
本文介绍了事件是不是田 - 我不明白这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在深入 C#(的优秀图书到目前为止),斯基特解释的事件不是领域的。我读这节很多次,我不明白为什么的区别有什么差别。

In C# in depth (an excellent book thus far), Skeet explains events aren't fields. I read this section many times and I don't understand why the distinction makes any difference.

我的那些混淆事件和委托实例开发商之一。在我看来,它们是相同的。两者不只是一种间接的形式?我们可以多播两者。事件是设置为现场速记......肯定。但是,我们要添加或删除处理。堆叠起来被称为事件触发时。难道我们做代表同样的事情,堆叠起来,并呼吁调用?

I am one of those developers that confuse events and delegate instances. In my mind, they are the same. Aren't both just a form of indirection? We can multicast both. An event is setup as a field as shorthand...sure. But, we are adding or removing handlers. Stacking them up to be called when the event fires. Don't we do the same thing with delegates, stack them up and call invoke?

推荐答案

其他答案基本上是正确的,但这里的另一种方式来看待它:

The other answers are basically correct, but here's another way to look at it:

我的那些混淆事件和委托实例开发商之一。在我看来,它们是相同的。

I am one of those developers that confuse events and delegate instances. In my mind, they are the same.

这是老说关于不只见树木不见森林浮现在脑海。我做的区别在于事件是在一个更高的语义层比委托实例的一个领域。事件告诉类型您好,我是喜欢告诉你有事时一型消费者。该类型源的活动;这是它的公共合同的一部分。

An old saying about not seeing the forest for the trees comes to mind. The distinction that I make is that events are at a higher "semantic level" than a field of delegate instance. An event tells the consumer of the type "hi there, I am a type that likes to tell you when something happens". The type sources an event; that's part of its public contract.

如何,作为一个实现细节,该类别选择跟踪谁爱好收听该事件,和什么时候来告诉用户该事件是发生的事情,是类的业务。它发生在通常与多播委托这样做,但是这是一个实现细节。它是这样一个共同的实现细节,这是合理的,将两者混为一谈,但我们确实有两个不同的东西:一个公共表面和私人实现细节

How, as an implementation detail, that class chooses to keep track of who is interested in listening to that event, and what and when to tell the subscribers that the event is happening, is the business of the class. It happens to typically do so with a multicast delegate, but that's an implementation detail. It is such a common implementation detail that it is reasonable to confuse the two, but we really do have two different things: a public surface, and a private implementation detail.

同样地,属性描述对象的语义:一个客户都有一个名称,所以Customer类具有Name属性。你可能会说,他们的名字是客户的财产,但你绝不会说,他们的名字是的字段的顾客的;这是一个特定类的实现细节,而不是一个关于业务语义事实。一个属性通常实现为一个字段是技工类的私人细节。

Similarly, properties describe the semantics of an object: a customer has a name, so a Customer class has a Name property. You might say that "their name" is a property of a customer, but you would never say that "their name" is a field of a customer; that's an implementation detail of a particular class, not a fact about the business semantics. That a property is typically implemented as a field is a private detail of the class mechanics.

这篇关于事件是不是田 - 我不明白这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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