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 - 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)的更多相关文章
- 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 ...
- 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 ...
- Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)
By now, I have shown the following usages of delegates... Callback and Multicast delegatesEventsOne ...
- 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 ...
- 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 ...
- 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, ...
- 11.Events
1.A type that defines an event member allows the type (or instances of the type) to notify other obj ...
- VB.NET vs. C#
VB.NET Program Structure C# Imports System Namespace Hello Class HelloWorld Overloads Shar ...
- [转]c#.NET和VB.NET语法的比较
本文转自:http://www.cnblogs.com/lify0407/archive/2007/08/01/838589.html c#.NET和VB.NET语法的比较 VB.NET C# C ...
随机推荐
- CSS条件注释
由于浏览器版本的不同,对CSS里某些元素的解释也不一样,针对浏览器版本不同而选择不同CSS的代码,其实我们还可以利用条件注释的方法来达到类似的目的,什么是条件注释,在此简单介绍一下,无非就是一些if判 ...
- 关于Unity中定时器的简易使用
定时器 一段指定的时间后执行某个函数或者某个语句 用法 //定时器写法1 flaot total_time; void Update(){ this.total_time += (Time.delta ...
- js dom添加回车事件
<!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta ...
- spatial transformer networks 这篇论文
大致看了看这个paper, 很novel. 我的观点: 在traditional convolutional neural netwoks 中,我们通常会depend 于 extracting fea ...
- 【吉比特】G-bits2017技术类岗位编程题
求素数 输入M.N,1 < M < N < 1000000,求区间[M,N]内的所有素数的个数.素数定义:除了1以外,只能被1和自己整除的自然数称为素数 输入描述: 两个整数M,N ...
- android 解决输入法键盘遮盖布局问题
/** * @param root 最外层布局,需要调整的布局 * @param scrollToView 被键盘遮挡的scrollToView,滚动root,使scrollToVie ...
- 第1章:认识Shell脚本
第一章:认识Shell脚本 1.1.什么是Shell Shell是系统的用户界面,提供了用户与内核进行交互操作的一种接口.它接收用户输入的命令并把它送入内核去执行. 实际上Shell是一个命令解释器 ...
- How to suppress 'Maybe this is program method' warnings from ProGuard
11down votefavorite 2 I'm using ProGuard with my Android application and I'm running getting the war ...
- Nginx安装 默认虚拟主机 Nginx用户认证 Nginx域名重定向
Nginx安装 cd /usr/local/src (http://nginx.org/en/download.html) wget http://nginx.org/download/nginx-1 ...
- CentOS 经常使用系统命令
# uname -a # 查看内核/操作系统/CPU信息# head -n 1 /etc/issue # 查看操作系统版本号# cat /proc/cpuinfo # 查看CPU信息# ...