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)的更多相关文章

  1. 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 ...

  2. 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 ...

  3. Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)

    By now, I have shown the following usages of delegates... Callback and Multicast delegatesEventsOne ...

  4. 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 ...

  5. 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 ...

  6. 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, ...

  7. 11.Events

    1.A type that defines an event member allows the type (or instances of the type) to notify other obj ...

  8. VB.NET vs. C#

    VB.NET Program Structure C# Imports System Namespace Hello    Class HelloWorld        Overloads Shar ...

  9. [转]c#.NET和VB.NET语法的比较

    本文转自:http://www.cnblogs.com/lify0407/archive/2007/08/01/838589.html c#.NET和VB.NET语法的比较   VB.NET C# C ...

随机推荐

  1. Mac和Linux下pip更换源

    cd ~mkdir .pip vim .pip/pip.conf 在pip.conf中写入 [global]timeout = 6000index-url = https://pypi.tuna.ts ...

  2. (笔记)Mysql命令use:使用数据库

    use命令可以让我们来使用数据库. use命令格式: use <数据库名>; 例如,如果xhkdb数据库存在,尝试存取它:   mysql> use xhkdb;屏幕提示:Datab ...

  3. Java如何显示所有正在运行的线程?

    在Java编程中,如何显示所有正在运行的线程? 以下示例演示如何使用getName()方法显示所有正在运行的线程的名称. package com.yiibai; public class Displa ...

  4. 关于对最新HTML总结PPT讲稿的分享

    如果大家还记得HTML,那么2009年的时候可能当时还是HTML1.0时代,而国际化的标准才刚刚开始,对于TABLE表格的使用,还有就是一些常用的标签都是及为简单的,因为当时的代码都是接近于短码,所以 ...

  5. OpenMP并行编程应用—加速OpenCV图像拼接算法

    OpenMP是一种应用于多处理器程序设计的并行编程处理方案,它提供了对于并行编程的高层抽象.仅仅须要在程序中加入简单的指令,就能够编写高效的并行程序,而不用关心详细的并行实现细节.减少了并行编程的难度 ...

  6. IE10弹窗showModalDialog关闭之后提示SCRIPT5011:不能执行已释放的Script代码

    在Web开发中,经常使用showModalDialog弹窗 今天遇到一个小问题,IE10中弹窗关闭之后提示SCRIPT5011:不能执行已释放的Script代码 网上搜罗了一些资料,发现大多都提到对象 ...

  7. tp5数据输出

    法一:系统配置 'default_return_type'=>'json' 法二:输出设置 namespace app\index\controller; class Index { publi ...

  8. windows使用技巧和工具(后面可能更新linux)

    *:希望广大网友有什么建议或者好的用法工具.也能够在以下评论. 希望这是一个能够让我们更好工作起来的帖子. 工作也能舒适和开心呢. 想着好久没写过博客了吧.今天就写一篇关于windows的使用的吧.我 ...

  9. js sendBeacon

    页面性能日志: DNS解析耗时 TCP链接耗时 SSL安全链接耗时 网络请求耗时 DOM解析耗时 资源加载耗时 首包时间 白屏时间 首次可交换时间 Dom Ready时间 页面完全加载时间. 如某些统 ...

  10. ★Wireshark基本介绍和学习TCP三次握手

    之前写过一篇博客:用 Fiddler 来调试HTTP,HTTPS. 这篇文章介绍另一个好用的抓包工具wireshark, 用来获取网络数据封包,包括http,TCP,UDP,等网络协议包. 记得大学的 ...