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. .net操作oracle,一定要用管理员身份运行 visual studio 啊,切记切记,免得报奇怪的错误。

    .net操作oracle,一定要用管理员身份运行 visual studio 啊,切记切记,免得报奇怪的错误.

  2. 【转】IT族室内锻炼身体的小妙招

    上班族.久坐族近年的健康状况令人堪忧,由于缺乏运动加上长期面对辐射,使上班族身体状况越来越差.专家建议上班族应多加运动,只需小小的动作就能轻松获得健康! 梳头:用木梳从前额至头顶部向后部梳刷,逐渐加快 ...

  3. Android 8 Wifi 初始化过程

    记录一下wifi初始化过程. packages/apps/Settings/src/com/android/settings/wifi/WifiSettings.java public void on ...

  4. QTreeView 限制特定的深度、特定深度下的列 是否可以编辑

    QTreeView 限制特定的深度.特定深度下的列 是否可以编辑 # # C_TreeView # 在QTreeView基础上增加限制特定深度.特定列是否可以编辑 # class C_TreeView ...

  5. Linux下seq的使用

    seq - print a sequence of numbers [root@gechong ~]# man seq 主要有一下三个参数 -f:用来格式化输出 -s:用来指定分隔符号,默认是回车 - ...

  6. 定时任务quartz与spring的集成

    我想要在spring的集成框架中使用spring , 暂时采用quartz 根据下面的几篇博客实现了(懒得说了,直接丢链接): Quartz实现动态定时任务 Spring 3整合Quartz 2实现定 ...

  7. C# 一个多层循环中,break一次能跳出几个循环?

    public class BreakTest { public static void main(String[] args) { ; x<; x++) { ; y<; y++) { ; ...

  8. 使用 SharpSvn 执行 svn 操作的Demo

    1. SharpSvn简介 SharpSvn.dll 是为.Net 2.0-4.0+ 应用提供的 Subversion Client API,更多详细介绍请见 https://sharpsvn.ope ...

  9. linux echo命令

    该篇文章转载于:http://www.cnblogs.com/ZhangShuo/articles/1829589.html linux的echo命令, 在shell编程中极为常用, 在终端下打印变量 ...

  10. 找不到 android-support-v4 解决办法

    Project->properties->Java Build Path->Libraries->Add External Jars中加入sdk目录下的extras/andro ...