事件不是字段 - 我不明白 [英] Events aren't fields - I don't get it

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

问题描述

C#深入(迄今为止很好的书),Skeet解释说>事件不是字段。我读了这个部分很多次,我不明白为什么这个区别有什么区别。

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.

我是那些混淆事件和委托实例的开发人员之一。在我看来,他们是一样的。不仅仅是一种间接的形式吗?我们可以组播两者。事件被设置为一个字段作为速记...确定。但是,我们正在添加或删除处理程序。当事件触发时,将它们堆叠起来。我们不要和代理人做同样的事情,把它们叠加起来并调用invoke吗?

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天全站免登陆