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. js在IE与firefox的差别。。。

    1.firefox不能对innerText支持.firefox支持innerHTML但却不支持innerText,它支持textContent来实现innerText,不过默认把多余的空格也保留了.如 ...

  2. ryu学习笔记(2) 之 ryu-manager运行报错

    http://blog.csdn.net/haimianxiaojie/article/details/48769653 ryu在使用的时候最常出现的报错是:address already in us ...

  3. 常用网络名词mark & 网络学习笔记

    自 治 系 统 ( A S, A utonomous System ) IGP 内部网关协议 I n t e r i o r G a t e w a y P r o t o c o l 域 内 选 路 ...

  4. 利用altium怎么生成PDF及怎么1:1打印文档

    画完板子之后,还要生成原理图PDF文档,供其他设计人员参考和指正. 上图红框标注的两个地方,分别用于打印预览设置和生成原理图PDF.那么若是生成原理图PDF文档,则选择smart PDF即可. 点击s ...

  5. 【转载】linux下的mount命令详解;

    以下内容来自:http://blog.csdn.net/clozxy/article/details/5299054 http://linux.chinaunix.net/techdoc/system ...

  6. Linux网络的设置

    一.介绍 目的:使Linux可以正常上网,前提是物理机可以上网 软件环境: 虚拟机版本: VMware Workstation 12, Linux系统版本:CentOS 7.3 二.设置网络 1,在登 ...

  7. Spring JDBC对象批量操作

    以下示例将演示如何使用spring jdbc中的对象进行批量更新.我们将在单次批次操作中更新student表中的记录. student表的结果如下 - CREATE TABLE student( id ...

  8. mysql监控工具sqlprofiler,类似sqlserver的profiler工具

    最近无意发现了mysql的客户端监控工具“Nero Profile SQL”,刚开始还不知道怎么使用,经过半小时摸索,现将使用步骤写下来. 背景:开发的时候,如果数据存储层这块使用EF,或者其他orm ...

  9. 某软件大赛C#版考题整理——【单选题】

    多选题:http://www.cnblogs.com/zxlovenet/p/3525849.html 编程题:http://www.cnblogs.com/zxlovenet/p/3525854.h ...

  10. PLSQL Developer删除奇葩表出现异常ORA-00942: 表或试图不存在

    简单描述一下问题:发现数据库里有两个名称相同的表,不同的是PLSQL Developer里一个表名显示是大写,而另一个表名显示是小写 一般情况下,无论建表语句是大写,还是小写,因Oracle是区分大小 ...