In my previous post, I spoke about a few very basic and simple reasons of using delegates - primarily callback. In this post, I'll talk about creating Events using delegates.

I have tried to annotate the class with comments so that it is easy to comprehend. But IMHO, the best way to figure out what's going on is to copy/paste the following code and create breakpoint in the Main() class and hit F11 to step into the code. You will notice that Events are based on the Observer or Publish/Subscribe design pattern.

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 through the code and see for yourself how easy this is!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace DelegatesAndEvents
{
//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 //To comply with Rule 3 we create a LoggerEventArgs which is derived from EventArgs
class LoggerEventArgs : EventArgs
{
//constructor to initialize the UserName property
public LoggerEventArgs(string UserName)
{
this.username = UserName;
} string username;
public string UserName
{
get { return username; }
}
}; //To comply with Rule 1 and 2, in the publisher class we created a delegate and event declaration
class InventoryManager // Publisher
{
public delegate void LoggerEventHandler(object source, LoggerEventArgs e);
public event LoggerEventHandler OnInventoryUpdate; //This method will fire an event called OnInventoryUpdate whenever called
public void LogEvent(string username)
{
LoggerEventArgs e = new LoggerEventArgs(username);
if (OnInventoryUpdate != null)
{
Console.WriteLine("LogEvent > Raising events to all subscribers...\n");
OnInventoryUpdate(this, e);
}
}
}; class InventoryLogger // Subscriber
{
InventoryManager inventoryManager;
public InventoryLogger(InventoryManager inventoryManager)
{
Console.WriteLine("InventoryWatcher > Subscribing to OnInventoryUpdate event...\n");
this.inventoryManager = inventoryManager; //Wiring the event so that the event is fired
inventoryManager.OnInventoryUpdate +=
new InventoryManager.LoggerEventHandler(OnInventoryUpdate);
} void OnInventoryUpdate(object source, LoggerEventArgs e)
{
Console.WriteLine("The guy who changed this inventory was... " + e.UserName);
}
} class DelegateEvents
{
public static void Main()
{
InventoryManager inventoryManager = new InventoryManager(); Console.WriteLine("Main > Instantiating the subscriber... \n\n");
InventoryLogger inventoryLog = new InventoryLogger(inventoryManager); inventoryManager.LogEvent("Rahul Soni");
Console.ReadLine();
}
};
}

In the next post, I will talk about Asynchronous callbacks using delegates.

转: http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in-C-Part-2-(Events).aspx

Explaining Delegates in C# - Part 2 (Events 1)的更多相关文章

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

  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. 为什么Java匿名内部类访问的外部局部变量或参数需要被final修饰

    大部分时候,类被定义成一个独立的程序单元.在某些情况下,也会把一个类放在另一个类的内部定义,这个定义在其他类内部的类就被称为内部类,包含内部类的类也被称为外部类. class Outer { priv ...

  2. r语言 function 指定多个返回值

    # Goals: To write functions # To write functions that send back multiple objects. # FIRST LEARN ABOU ...

  3. 认识J2EE规范或标准以及J2EE和JEE有什么不同?

    1. J2EE实际上是一组规范(新手对规范这个词可能云里雾里的,没有办法,JAVA概念太多了,大部分概念慢慢就会理解),没错,J2EE这个概念并不是某种技术,而是一堆规范(实现意义上可以说是一堆技术) ...

  4. Linux SD卡驱动开发(四) —— SD 控制器之真正的硬件操作

    前面对SD卡控制器有了一个主要的介绍.事实上SD控制器层更过的意义是为core层提供一种操作SD卡硬件的一种方法.当然不同的控制器对硬件控制的方法不尽同样,可是他们终于都能像core层提交一个统一的封 ...

  5. ICMP Ping模版实现对客户端网络状态的监控

    Zabbix使用外部命令fping处理ICMP ping的请求,fping不包含在zabbix的发行版本中,需要额外去下载安装fping程序,安装完毕之后需要zabinx_server.conf中的参 ...

  6. 10个样式各异的CSS3 Loading加载动画

    前几天我在园子里分享过2款很酷的CSS3 Loading加载动画,今天又有10个最新的Loading动画分享给大家,这些动画的样式都不一样,实现起来也并不难,你很容易把它们应用在项目中,先来看看效果图 ...

  7. Dependency Scopes(maven)

    Dependency scope 是用来限制Dependency的作用范围的, 影响maven项目在各个生命周期时导入的package的状态. 自从2.0.9后,新增了1种,现在有了6种scope: ...

  8. lnmp手动新建虚拟机

    1.在home/wwwroot/zhongjie   新建zhongjie文件夹 2.在usr/local/nginx/conf/vhost/zhongjie.conf    新建配置文件zhongj ...

  9. mongodb可视化工具连接报错

    failed to get address info 这时候注意看一下 IP地址是不是加了http了,如果加了一定要去掉.IP地址是不加http的.去掉就能正常连接了.

  10. Window 10 :如何彻底关闭:Windows Defender Service(2015-12-20日更新)

    Window 10 :如何彻底关闭:Windows Defender Service? 网上流传的什么组策略gpeidt.msc方法,什么安装其他的杀软之类的方法都很麻烦,且有弊病! 其实很简单: 利 ...