delegate vs event
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.
publicclassAnimal{publicActionRun{get;set;}publicvoidRaiseEvent(){if(Run!=null){Run();}}}
To use the delegate, you should do something like this:
Animal animal=newAnimal();animal.Run+=()=>Console.WriteLine("I'm running");animal.Run+=()=>Console.WriteLine("I'm still running");animal.RaiseEvent();
This code works well but you could have some weak spots:
For example, if I write this:
animal.Run+=()=>Console.WriteLine("I'm running");animal.Run+=()=>Console.WriteLine("I'm still running");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:
if(animal.Run!=null){animal.Run();}
To avoid these weak spots you can use events in c#.
Example with Event
Your "event version" of the Animal class will looks like:
publicclassArgsSpecial:EventArgs{publicArgsSpecial(string val){Operation=val;}publicstringOperation{get;set;}}publicclassAnimal{// Empty delegate. In this way you are sure that value is always != null// because no one outside of the class can change it.publiceventEventHandler<ArgsSpecial>Run=delegate{};publicvoidRaiseEvent(){Run(this,newArgsSpecial("Run faster"));}}
to call events
Animal animal=newAnimal();animal.Run+=(sender, e)=>Console.WriteLine("I'm running. My value is {0}", e.Operation);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:
// Error: the event 'delegateEvent.Animal.Run' can only appear on the left hand side of += or -=// (except when used from within the type 'delegateEvent.Animal')animal.Run(animal,newArgsSpecial("Run slower"));
4. Event can be included in an interface declaration, whereas a delegate field cannot.
delegate vs event的更多相关文章
- 浅谈c#中的delegate和event了
一.开篇忏悔 对自己最拿手的编程语言C#,我想对你说声对不起,因为我到现在为止才明白c#中的delegate和event是怎么用的,惭愧那.好了,那就趁着阳光明媚的早晨简单来谈谈delegate和ev ...
- 第一章、C#委托和事件(Delegate、Event、EventHandler、EventArgs)
第一章.C#委托和事件(Delegate.Event.EventHandler.EventArgs) 分类: 学习笔记-C#网络编程2012-12-08 14:10 7417人阅读 评论(3) 收藏 ...
- delegate和event
经过查阅资料和自己的理解整理出来的,欢迎大家指教. delegate和event 何时使用: 异步的时候,比如加载完成通知. 需要回调的时候,比如按钮点击.动画播放结束等. 发送事件通知的时候. 比如 ...
- .NET 中易混淆的概念(Delegate vs Event)
事件(event)是一个非常重要的概念,我们的程序时刻都在触发和接收着各种事件:鼠标点击事件,键盘事件,以及处理操作系统的各种事件.所谓事件就是 由某个对象发出的消息.比如用户按下了某个按钮,某个文件 ...
- 观察者模式与.NET的delegate、event机制
1.引言 最近在写一些程序玩的时候,接触到了delegate(委托)和event(事件),网上查找了很多的资料,有些博文说可以把delegate近似当做C++当中的函数指针来看,由于自己本身对C++的 ...
- [转] C#中的delegate 和 event
转至:here 终于会用c#中的delegate(委托) 作者:qq826364410 引言 Delegate是Dotnet1.0的时候已经存在的特性了,但由于在实际工作中一直没有机会使用Delega ...
- C#: Delegate and Event
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- delegate 和 event
delegate 和 event 观察者模式 这里面综合了几本书的资料. 需求 有这么个项目: 需求是这样的: 一个气象站, 有三个传感器(温度, 湿度, 气压), 有一个WeatherData对象, ...
- [转载]C#委托和事件(Delegate、Event、EventHandler、EventArgs)
原文链接:http://blog.csdn.net/zwj7612356/article/details/8272520 14.1.委托 当要把方法作为实参传送给其他方法的形参时,形参需要使用委托.委 ...
- C#中Delegate和Event以及它们的区别(转载)
一.Delegate委托可以理解为一个方法签名. 可以将方法作为另外一个方法的参数带入其中进行运算.在C#中我们有三种方式去创建委托,分别如下: public delegate void Print( ...
随机推荐
- UVa 573 - The Snail
题目大意:有一只蜗牛位于深一个深度为h米的井底,它白天向上爬u米,晚上向下滑d米,由于疲劳原因,蜗牛白天爬的高度会比上一天少f%(总是相对于第一天),如果白天爬的高度小于0,那么这天它就不再向上爬,问 ...
- 安装了C
2014-04-09 13:19:30 大学里看的第一本编程书籍,就是C.但是一直没有编译. 今天首次安装,我也佩服当初我是怎么通过C二级的. 上午写了sds手册.其中的制图用的visio制图,非常好 ...
- UVa 10033 - Interpreter
题目大意:模拟题,有一些寄存器和随机访问内存,给你一些指令以及它们代表的操作,模拟操作即可. #include <cstdio> #include <cstring> #def ...
- iOS 专题 之 界面开发 之 控件
iOS 之 UIViewController iOS 之 Navagation Button iOS 之 UIButton iOS 之 UITextField iOS 之 UIStackView iO ...
- PHP使用array_intersect()函数求数组交集
在PHP中求数组的交集,我们可以与PHP给我们提供的现成函数:array_intersect(),其用法格式为: array array_intersect(array array1,array ar ...
- C++ STL算法系列1---unique , unique_copy函数
一.unique函数 类属性算法unique的作用是从输入序列中“删除”所有相邻的重复元素. 该算法删除相邻的重复元素,然后重新排列输入范围内的元素,并且返回一个迭代器(容器的长度没变,只是元素顺序 ...
- --@angularJS--指令之单个点击展开demo
1.expander.html: <!DOCTYPE HTML><html ng-app="app"><head> <title&g ...
- JS前端的分享功能
给网页加上分享代码,借助网友的力量推广网站,目前已经很流行了 以下是网页代码 QQ空间分享代码如下: <a href="javascript:void(0);" onclic ...
- NodeJS的Cluster模块使用
一.前言大家都知道nodejs是一个单进程单线程的服务器引擎,不管有多么的强大硬件,只能利用到单个CPU进行计算.所以,有人开发了第三方的cluster,让node可以利用多核CPU实现并行. 随着n ...
- FMS+NGINX打造高带宽利用率的流媒体(音频+视频)环境
fms自身已经拥有了httpd,用来给客户端访问用,例如通过http的音频播放.众所周知,非专业的httpd自然有不专业之处,例如我遇到的情况就是经常http服务假死,或者在访问量庞大的时候会无缘无故 ...