为什么我们需要"事件"关键字,同时定义事件? [英] Why do we need the "event" keyword while defining events?

查看:204
本文介绍了为什么我们需要"事件"关键字,同时定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我们需要活动关键字在定义事件的时候,我们可以做同样的事情,而不使用事件的关键字,只需使用代表。

I don't understand why do we need the "event" keyword while defining events, when we can do the same thing without using "event" keyword, just by using the delegates.

例如。

public delegate void CustomEventHandler(int a, string b);
public event CustomEventHandler customEvent;
customEvent += new CustomEventHandler(customEventHandler);
customEvent(1,"a"); // Raising the event

在这里,如果我从第二行中删除事件关键字,那么我也可以通过调用委托引发事件。谁能告诉我这是为什么事件关键字需要?

Here if I remove the "event" keyword from the second line, then also I can raise the event by invoking the delegate. Can anybody please tell me why is this event keyword needed ?

推荐答案

字段的事件和委托类型的公共领域的的相似,但实际上却是非常不同的。

Field-like events and public fields of delegate types look similar, but are actually very different.

这是事件是从根本上就像一个属性 - 这是一对添加/删除(而不是get / set方法的属性)的方法。在声明现场般的事件(即,一个在您不指定添加/删除位自己)创建一个公共活动和私人支持字段。这可以让你提高的情况下,私下却允许公开认购。随着公共委托场,的可以删除其他人的事件处理程序,提高了事件本身,等等 - 这是一个封装灾难

An event is fundamentally like a property - it's a pair of add/remove methods (instead of the get/set of a property). When you declare a field-like event (i.e. one where you don't specify the add/remove bits yourself) a public event is created, and a private backing field. This lets you raise the event privately, but allow public subscription. With a public delegate field, anyone can remove other people's event handlers, raise the event themselves, etc - it's an encapsulation disaster.

更多关于事件(与代表)阅读关于这一主题我的文章。 (在某些时候,我需要更新此为C#4,这改变字段的事件非常轻微,它的要点仍然是正确的,但。)

For more on events (and delegates) read my article on this topic. (At some point I need to update this for C# 4, which changes field-like events very slightly. The gist of it is still correct though.)

这篇关于为什么我们需要"事件"关键字,同时定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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