What are the differences between delegate and an event?

An event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list. 

To understand the differences you can look at 2 examples below:

Example with Delegate

First let's try to implement an "event trigger" by using "delegate" instead of "event". 

in this case, the example delegate Run is an Action - that is a kind of delegate that doesn't return a value.

  1. publicclassAnimal
  2. {
  3. publicActionRun{get;set;}
  4. publicvoidRaiseEvent()
  5. {
  6. if(Run!=null)
  7. {
  8. Run();
  9. }
  10. }
  11. }

To use the delegate, you should do something like this:

  1. Animal animal=newAnimal();
  2. animal.Run+=()=>Console.WriteLine("I'm running");
  3. animal.Run+=()=>Console.WriteLine("I'm still running");
  4. animal.RaiseEvent();

This code works well but you could have some weak spots

For example, if I write this:

  1. animal.Run+=()=>Console.WriteLine("I'm running");
  2. animal.Run+=()=>Console.WriteLine("I'm still running");
  3. animal.Run=()=>Console.WriteLine("I'm sleeping");

with the last line of code, I have overridden the previous behaviors just with one missing + (I have used = instead of +=)

Another weak spot is that every class which uses your Animal class can raise the Run event without calling the public RaiseEvent function, but with code snippet like:

  1. if(animal.Run!=null)
  2. {
  3. animal.Run();
  4. }

To avoid these weak spots you can use events in c#.

Example with Event

Your "event version" of the Animal class will looks like:

  1. publicclassArgsSpecial:EventArgs
  2. {
  3. publicArgsSpecial(string val)
  4. {
  5. Operation=val;
  6. }
  7. publicstringOperation{get;set;}
  8. }
  9. publicclassAnimal
  10. {
  11. // Empty delegate. In this way you are sure that value is always != null
  12. // because no one outside of the class can change it.
  13. publiceventEventHandler<ArgsSpecial>Run=delegate{};
  14. publicvoidRaiseEvent()
  15. {
  16. Run(this,newArgsSpecial("Run faster"));
  17. }
  18. }

to call events

  1. Animal animal=newAnimal();
  2. animal.Run+=(sender, e)=>Console.WriteLine("I'm running. My value is {0}", e.Operation);
  3. animal.RaiseEvent();

Differences:

1. You aren't using a public property but a public field. 

Using events, the compiler protects your fields from unwanted access 

2. Event can't be assigned directly. 

In this case, it is impossible to override the previous behaviors by using = instead of +=. 

3. No one outside of your class can raise the event. 

Even the Run event is public, a compiler error will occur if someone tries to raise the event with code snippet below:

  1. // Error: the event 'delegateEvent.Animal.Run' can only appear on the left hand side of += or -=
  2. // (except when used from within the type 'delegateEvent.Animal')
  3. animal.Run(animal,newArgsSpecial("Run slower"));

4. Event can be included in an interface declaration, whereas a delegate field cannot.

delegate vs event的更多相关文章

  1. 浅谈c#中的delegate和event了

    一.开篇忏悔 对自己最拿手的编程语言C#,我想对你说声对不起,因为我到现在为止才明白c#中的delegate和event是怎么用的,惭愧那.好了,那就趁着阳光明媚的早晨简单来谈谈delegate和ev ...

  2. 第一章、C#委托和事件(Delegate、Event、EventHandler、EventArgs)

    第一章.C#委托和事件(Delegate.Event.EventHandler.EventArgs) 分类: 学习笔记-C#网络编程2012-12-08 14:10 7417人阅读 评论(3) 收藏  ...

  3. delegate和event

    经过查阅资料和自己的理解整理出来的,欢迎大家指教. delegate和event 何时使用: 异步的时候,比如加载完成通知. 需要回调的时候,比如按钮点击.动画播放结束等. 发送事件通知的时候. 比如 ...

  4. .NET 中易混淆的概念(Delegate vs Event)

    事件(event)是一个非常重要的概念,我们的程序时刻都在触发和接收着各种事件:鼠标点击事件,键盘事件,以及处理操作系统的各种事件.所谓事件就是 由某个对象发出的消息.比如用户按下了某个按钮,某个文件 ...

  5. 观察者模式与.NET的delegate、event机制

    1.引言 最近在写一些程序玩的时候,接触到了delegate(委托)和event(事件),网上查找了很多的资料,有些博文说可以把delegate近似当做C++当中的函数指针来看,由于自己本身对C++的 ...

  6. [转] C#中的delegate 和 event

    转至:here 终于会用c#中的delegate(委托) 作者:qq826364410 引言 Delegate是Dotnet1.0的时候已经存在的特性了,但由于在实际工作中一直没有机会使用Delega ...

  7. C#: Delegate and Event

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  8. delegate 和 event

    delegate 和 event 观察者模式 这里面综合了几本书的资料. 需求 有这么个项目: 需求是这样的: 一个气象站, 有三个传感器(温度, 湿度, 气压), 有一个WeatherData对象, ...

  9. [转载]C#委托和事件(Delegate、Event、EventHandler、EventArgs)

    原文链接:http://blog.csdn.net/zwj7612356/article/details/8272520 14.1.委托 当要把方法作为实参传送给其他方法的形参时,形参需要使用委托.委 ...

  10. C#中Delegate和Event以及它们的区别(转载)

    一.Delegate委托可以理解为一个方法签名. 可以将方法作为另外一个方法的参数带入其中进行运算.在C#中我们有三种方式去创建委托,分别如下: public delegate void Print( ...

随机推荐

  1. sublime text2的插件熟悉

    今天加班,开会.于是整理下sublime text的插件. 1.安装了tag插件.负责html的格式化.从百度云下载了文件,放入了插件包的目录下. 2.启用了alignment 快捷键 ctr+alt ...

  2. UVa 11340 - Newspaper

    题目大意:报社根据文章中不同字符的价值付费给作者,给出字符的价值,计算一篇文章应付多少钱给作者. 先统计文章中每个字符出现的次数,再计算价值.直接寻址表(Direct Addressing Table ...

  3. 用scala实现一个基于TCP Socket的快速文件传输程序

    这是用scala实现的一个简单的文件传输程序. 服务端 package jpush import java.io.{DataInputStream, File, FileOutputStream} i ...

  4. ubuntu系统中crontab的使用介绍

    1.创建crontab任务 用户hancool

  5. Java中间件:淘宝网系统高性能利器(转)

    淘宝网是亚太最大的网络零售商圈,其知名度毋庸置疑,吸引着越来越多的消费者从街头移步这里,成为其忠实粉丝.如此多的用户和交易量,也意味着海量的信息处理,其背后的IT架构的稳定性.可靠性也显得尤为重要.那 ...

  6. Delphi-IP地址的隐藏

    IP地址的隐藏 一.前言 本文主要介绍如何在程序中实现IP地址的隐藏.其实这篇东西不算我写的.其中<IP头结构>部分我懒得打字,故复制.粘贴了孤独剑客的文章,先说声谢谢!代码部分参考了外国 ...

  7. 在vue-cli项目中安装node-sass

    1,使用save会在package.json中自动添加. ----npm install node-sass  --save ----npm install sass-loader  --save 2 ...

  8. PHP 中使用socket

    一.开启socket phpinfo();查看是否开启了socket扩展,否则在php.ini中开启. 二.服务器端代码的写法 <?php error_reporting(E_ALL); set ...

  9. ORACLE Postgresql中文排序

    当我们order排序不能够实现我们想要的内容时候,尝试一下NLSSORT这个函数吧 他不仅仅按照姓氏排序,名也会排序: nls_param用于指定语言特征,格式为nls_sort      = sor ...

  10. Hibernate最简单教程

    其实Hibernate本身是个独立的框架,它不需要任何web server或application server的支持.然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西, ...