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. Qt实现探测当前有没有网络连接(Wi-Fi)——QNetworkConfigurationManager.isOnline()

    1.只需要探测当前有没有连上Wi-Fi(不用获取网络状态),可以调用<QNetworkConfigurationManager>类. QNetworkConfigurationManage ...

  2. C/C++ 查看数组类型长短 , python的len的封装原理

    sizeof什么时间加括号什么时候不加括号? sizeof当用应用于一个表达式的时候不需要圆括号: 例如 sizeof  i; 如果运算符优先的时候需要: 例如sizeof(i+j); 方法一. in ...

  3. javaweb-Excel导入导出后台代码

    前言: 导入导出后台java代码写好很久了,但是...但是...前台不会写啊. 先把后台代码帖上吧 1.excelToDb package util; /** * 代码解释:此方法将传入一个URL,即 ...

  4. php模拟post提交数据,用处很多,可用来网站的采集,登陆等等

    1. [代码][PHP]代码 <?php //以程序登陆一个论坛登录为例 function bbslogin($user_login, $password, $host, $port = &qu ...

  5. JAVA组成原理及使用方法编辑环境及实现过程

    JAVA组成原理一.由四方面组成:1.Java编程语言2.Java类文件格式3.Java虚拟机4.Java应用程序接口 当编辑并运行一个Java程序时,需要同时涉及到这四种方面.二.使用文字编辑软件: ...

  6. Keepalived + Nginx + Tomcat 的高可用负载均衡架构搭建

    Keepalived + Nginx + Tomcat 的高可用负载均衡架构搭建 Nginx 是一个高性能的 HTTP反向代理服务器 Keepalived 是一个基于VRRP协议来实现的LVS服务高可 ...

  7. Linux网卡eth0变成eth1修改方法

    由于换了主板,集成网卡mac地址变了,70-persistent-net.rules中仍然保留了老网卡的内容,新网卡则被识别为eth1. 将表示老网卡的行注释掉,然后将表示新网卡的行中eth1改成et ...

  8. Enhance基本例子

    太晚了,有些东西没有补充,回头再补上. 先上Demo 1.要执行的方法 package enhancerTest; /** * Created by LiuSuSu on 2017/3/26. */ ...

  9. 经典炫酷的HTML5/jQuery动画应用示例及源码

    jQuery是一款普遍受前端开发者欢迎的Javascript框架,但是开发者貌似更关注jQuery开发的插件,海量的jQuery插件让前端开发者非常方便.HTML5的加入让jQuery这个家族更加丰富 ...

  10. php base64_encode,serialize对于存入数据表中字段的数据处理方案

    A better way to save to Database $toDatabse = base64_encode(serialize($data)); // Save to database $ ...