Explaining Delegates in C# - Part 3 (Events 2)
I was thinking that the previous post on Events and Delegates was quite self-explanatory. A couple of days ago, I received an email which said that may be it is not that good as to explain what I want to achieve in life through that event. So, I thought why not write another post on Delegates and Events to make things clearer from a practical (or may be not so practical, "BUT" just another simple and practical example. There is no harm in trying, after all...)
Here is the requirement...
You have a class with a special number. You have another (or may be a lot of other) class which is using it. The requirement now is that, whenever the special number is changed, all the other guys should be notified about what this number was and what it has become!
In this case,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace EventAndDelegateDemo
{
//There are 3 rules which are MANDATORY when you are planning to create events
//Rule 1> The delegate must be defined with two arguments
//Rule 2> These arguments always represent TWO objects…
// The Publisher (object that raised the event)
// Event Information object
//Rule 3> The 2nd object HAS to be derived from EventArgs //Step 1> Create a class that inherits from EventArgs (To comply with Rule 3)
class NotifyChangeEventArgs : EventArgs
{
//constructor to initialize the SpecialNumberOld and SpecialNumberNew property
public NotifyChangeEventArgs(int SpecialNumberOld, int SpecialNumberNew)
{
this.SpecialNumberNew = SpecialNumberNew;
this.SpecialNumberOld = SpecialNumberOld;
}
public int SpecialNumberNew { get; set; }
public int SpecialNumberOld { get; set; }
}; class SpecialNumberClass // Publisher
{
//Publisher declares a special delegate and event (Rule 1 & 2)
public delegate void SpecialNumberHandler(object source, NotifyChangeEventArgs e);
public event SpecialNumberHandler OnSpecialNumberUpdate; //Constructor to set the value of the _specialNumber directly.
//Notice that we are not setting the SpecialNumber property!
public SpecialNumberClass(int number)
{
_specialNumber = number;
} //This property will fire an event called OnSpecialNumberUpdate whenever called
//The effect is that is the special number is changed from outside, all the guys
//would be notified. It is upto them to listen to it or not listen to it.
private int _specialNumber;
public int SpecialNumber
{
get { return _specialNumber; }
//Put a breakpoint here on set and step into (F11)
set
{
if (OnSpecialNumberUpdate != null)
{
//This is the guy who would fire that notify event called OnSpecialNumberUpdate
//Basically, before you fire that event, you can set up that value for EventArgs
//In my case, I have set the value of e's old value and new value...
//to the _specialNumber and value (which would be the new value)
//Notice that we are just firing the events with appropriate EventArgs...
//We haven't thrown any output as such yet!!!!
NotifyChangeEventArgs e = new NotifyChangeEventArgs(_specialNumber, value);
Console.WriteLine("Raising Events to all the subscribers...\n");
OnSpecialNumberUpdate(this, e);
}
}
}
}; class SpecialNumberUpdateListener // Subscriber
{
//Here we are just creating a new Object called objSN for my SpecialNumberClass
SpecialNumberClass objSN; //In this method, I would go ahead and bind my event
public SpecialNumberUpdateListener(SpecialNumberClass spClass)
{
Console.WriteLine("SpecialNumber listener > Subscribing to the event...\n");
this.objSN = spClass; //Wiring the event so that the event is fired
spClass.OnSpecialNumberUpdate += new SpecialNumberClass.SpecialNumberHandler(OnSpecialNumberUpdate);
} //This is the event that would be invoked whenever you change the value
//Try putting a break point here and see how it gets hit when the number changes
//Also notice how we use the Event args to grab the details and finally print it out
void OnSpecialNumberUpdate(object source, NotifyChangeEventArgs e)
{
Console.WriteLine("The number has changed from {0} to {1} ", e.SpecialNumberOld, e.SpecialNumberNew);
}
} class EventDemo
{
public static void Main()
{
//Creating a new Special Number (Publisher) class with initial value of 20
SpecialNumberClass snc = new SpecialNumberClass();
//Creating a Subscriber/listener class
SpecialNumberUpdateListener s = new SpecialNumberUpdateListener(snc);
//Changing the value so that the event is triggered.
//Put a breakpoint and step into the code (F11)
snc.SpecialNumber = ;
Console.ReadLine();
}
}
}
转:http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in-C-Part-3-(Events-again).aspx
Explaining Delegates in C# - Part 3 (Events 2)的更多相关文章
- Explaining Delegates in C# - Part 2 (Events 1)
In my previous post, I spoke about a few very basic and simple reasons of using delegates - primaril ...
- Explaining Delegates in C# - Part 1 (Callback and Multicast delegates)
I hear a lot of confusion around Delegates in C#, and today I am going to give it shot of explaining ...
- Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)
By now, I have shown the following usages of delegates... Callback and Multicast delegatesEventsOne ...
- Explaining Delegates in C# - Part 4 (Asynchronous Callback - Way 1)
So far, I have discussed about Callback, Multicast delegates, Events using delegates, and yet anothe ...
- Explaining Delegates in C# - Part 7 (Asynchronous Callback - Way 4)
This is the final part of the series that started with... Callback and Multicast delegatesOne more E ...
- Explaining Delegates in C# - Part 5 (Asynchronous Callback - Way 2)
In this part of making asynchronous programming with delegates, we will talk about a different way, ...
- 11.Events
1.A type that defines an event member allows the type (or instances of the type) to notify other obj ...
- VB.NET vs. C#
VB.NET Program Structure C# Imports System Namespace Hello Class HelloWorld Overloads Shar ...
- [转]c#.NET和VB.NET语法的比较
本文转自:http://www.cnblogs.com/lify0407/archive/2007/08/01/838589.html c#.NET和VB.NET语法的比较 VB.NET C# C ...
随机推荐
- GCC编译错误小结
gcc编译时对’xxxx’未定义的引用问题可能错误 错误一: 没有实现xxxx 错误二: c++引用c语言so库,但是so库头文件没有extern "C" 错误三: 检查各个共享库 ...
- Win7系统中MySQL服务无法启动的解决方法
Win7系统中提示:本地无法启动MySQL服务,报的错误:1067,进程意外终止的解决方法.在本地计算机无法启动MYSQL服务错误1067进程意外终止.这种情况一般是my.ini文件配置出错了1.首先 ...
- L1&L2 Regularization
正则化方法:防止过拟合,提高泛化能力 在训练数据不够多时,或者overtraining时,常常会导致overfitting(过拟合).其直观的表现如下图所示,随着训练过程的进行,模型复杂度增加,在tr ...
- Axiom3D写游戏:用Overlay实现Mesh浏览.
从网上找了些资源,大多搜Ogre,Mesh资源,然后为了方便查看各个Mesh,以及对应骨骼动画.为了实用性,考虑放在原游戏窗口里实现.最开始打算窗口新建viewport来实现,后发现这种方式的局限性, ...
- WebGL 利用FBO完成立方体贴图。
这篇主要记录WebGL的一些基本要点,顺便也学习下如何使用FBO与环境贴图.先看下效果图(需要支持WebGL,Chrome,火狐,IE11). 主要实现过程如下,先用FBO输出当前环境在立方体纹理中, ...
- 第三百七十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapyd部署scrapy项目
第三百七十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapyd部署scrapy项目 scrapyd模块是专门用于部署scrapy项目的,可以部署和管理scrapy项目 下载地址:h ...
- Java如何格式化24小时格式的时间?
在Java中,如何格式化24小时格式的时间?? 此示例使用SimpleDateFormat类的sdf.format(date)方法将时间格式化为24小时格式(00:00-24:00). package ...
- e613. Modifying the Focus Traversal Order
JFrame frame = new JFrame(); JButton component1 = new JButton("1"); JButton component2 = n ...
- tushare使用
tushare是获取行情数据的一款免费软件 使用方法很简单, 先安装:pip install tushare 然后 import tushare as ts 即可. data = ts.get_k ...
- (转)YV12,I420,YUV420P的区别
YV12和I420的区别 一般来说,直接采集到的视频数据是RGB24的格式,RGB24一帧的大小size=width×heigth×3 Bit,RGB32的size=width×heigth×4, ...