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 ...
随机推荐
- hashMap 临界值初步理解
import java.util.*; public class Bs { //Integer.highestOneBit((number - 1) << 1)分解 public stat ...
- Python之collections.defaultdict
转自:http://www.jb51.net/article/88147.htm
- 今日Q群:QQ群众群友反馈问题的归纳总结
今日Q群:QQ群群友反馈问题的归纳总结 今天Q群里还算比较活跃,归纳总结后主要有以下几类问题: 一.如何在Excel中按指定规则对有颜色的单元格进行过滤删选 具体的解决办法,请参照今天发布微信 ...
- Linux 安装 MongoDB数据库
1下载: wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.7.tgz (下载较慢) 2.安装: mv mongodb-li ...
- unity---各种资源对应的格式
我们打包AssetBundle后,Unity3D会根据文件的后缀名将文件转换为特定的类型对象存储起来,我们后期获取时需要根据这些类型取出打包的数据,这里记录下不同后缀文件打包后的类型. 文本格式 支持 ...
- 对SingleTask和TaskAffinity的理解(转至 http://www.2cto.com/kf/201311/254450.html)
最近研究微信调起自己客户端的事情,对于SingleTask和TaskAffinity的理解又多了一些理解. 以前对于Android的四种LaunchMode有一些了解,其中比较有意思的就是Sing ...
- ios中layer动画和UIView动画代码总结
kCATransitionFade淡出 kCATransitionMoveIn覆盖原图 kCATransitionPush推出 kCATransitionReveal底部显出来 pageC ...
- Winform控件学习笔记【第四天】——WebBrowser
常用方法 Navigate(string urlString);//浏览urlString表示的网址 Navigate(System.Uri url);//浏览url表示的网址 Navigate(st ...
- C# 时间比较方法DateTime.Compare
public static int Compare(DateTime t1,DateTime t2) 返回值 类型:System..::.Int32 有符号数字,指示 t1 和 t2 的相对值. 值类 ...
- Linux 系统强制踢掉登录用户并禁止用户再次登录系统
标注:创建一个test测试用户,test用户使用Xshel工具ssh远程登录linux操作系统. 强制踢掉登录用户方法一: [root@cloucentos6 ~]# w ...