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. 关闭R语言载入包时候的警告

    options(warn =-1)

  2. python2 python3 字符串 编码格式 处理

    使用python的ctypes调用c语言中的函数,传入字符串,打印输出异常.解决方法记录于此. 参考连接: http://blog.csdn.net/u011546806/article/detail ...

  3. BIO、NIO、AIO系列二:Netty

    一.概述 Netty是一个Java的开源框架.提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序. Netty是一个NIO客户端,服务端框架.允许快速简 ...

  4. e769. 在按钮组中选择一个单选按钮

    // To create a radio button and button group, // see e768 创建单选按钮 // Select the radio button; the cur ...

  5. TPshop表结构

    tp_account_log -- 账户表 字段名 字段类型 默认值 描述 log_id mediumint(8) unsigned   日志id user_id mediumint(8) unsig ...

  6. James Whittaker的软件測试戒律(二)

    摘录自<探索式软件測试>(注:作者模仿了圣经十诫的语气和内容编写了软件測试戒律) 1.汝应用大量输入重复锤炼汝之应用程序 2.汝应贪图汝之邻居的应用程序 3.汝应亲自寻找睿智的预言家 4. ...

  7. motiMaker 软件安装测试

    背景: mitoMaker是一款线粒体/叶绿体组装的pipeline软件,可以从原始的下机数据开始,自动化的组装基因组,注释基因结构,最终生成genebank, fasta 等文件. 整个pipeli ...

  8. 如何在 Ubuntu 16.04,15.10,14.04 中安装 GIMP 2.8.16(类似于PS软件)

    GIMP 图像编辑器 2.8.16 版本在其20岁生日时发布了.下面是如何安装或升级 GIMP 在 Ubuntu 16.04, Ubuntu 15.10, Ubuntu 14.04, Ubuntu 1 ...

  9. Objective-C语法之字符串NSString去掉前后空格或回车符(可以是NSCharacterSet类型的其它字符)

    main.m #import <Foundation/Foundation.h> #import "NSString+Trim.h" int main(int argc ...

  10. 性能监控-TP理解

    首先给出Google到的答案: The tp90 is a minimum time under which 90% of requests have been served. tp90 = top ...