Using Delegates and Events 1 (来自一本49美元/817页2002年的书《C#.net web developers guide》)

guid|web

Using Delegates and Events
If you are familiar with Windows programming, you’ve most likely dealt with
callbacks. Callbacks are method calls that are executed when some event happens
http://www.syngress.com.70 Chapter 2 • Introducing C# Programming
during processing. For instance, a callback can be established to handle the pro-cessing
of an incoming message on a communications port. Another part of the
communications program can wait for messages on a communications port and
invoke the callback whenever a new message arrives. Function pointers perform
the same sort of tasks in straight C/C++ programs.
Delegates in C# improve on method callbacks in two areas. Delegates are type
safe, unlike callbacks in Windows programming. In addition, delegates can call
more than one callback when an event occurs. This is termed multicasting.
Delegates
Let’s extend our employees sample to use delegates.This sample simulates a back-ground
process that receives messages to add new employees to the employee list.
Our queue will be a static array, but in the real world it could be a message
queue (Microsoft Message Queue [MSMQ]), a socket, or some other type of
queue. The source code in Figure 2.7 shows the relevant portions of the sample
pertaining to delegates.The full source code for this sample is on the CD in the
file Delegates.cs.
Figure 2.7 Relevant Portions of the Delegates.cs Program Listing
using System;
using System.Collections;
/// <summary>
/// Contains the program entry point for the Delegates Sample.
/// </summary>
class DelegatesSample
{
static void Main( string[] args )
{
try
{
// Create a container to hold employees
Employees employees = new Employees(4);
// Create and drain our simulated message queue
EmployeeQueueMonitor monitor =
http://www.syngress.com
Continued.Introducing C# Programming • Chapter 2 71
new EmployeeQueueMonitor( employees );
monitor.start();
monitor.stop();
// Display the employee list on screen
Console.WriteLine(
"List of employees added via delegate:" );
foreach ( Employee employee in employees )
{
string name = employee.FirstName + " " +
employee.MiddleName + " " + employee.LastName;
string ssn = employee.SSN;
Console.WriteLine( "Name: {0}, SSN: {1}", name, ssn );
}
}
catch ( Exception exception )
{
// Display any errors on screen
Console.WriteLine( exception.Message );
}
}
}
/// <summary>
/// Simulates our message queue.
/// </summary>
class EmployeeQueueMonitor
{
// Delegate signature
http://www.syngress.com
Figure 2.7 Continued
Continued.72 Chapter 2 • Introducing C# Programming
public delegate void AddEventCallback( string FirstName,
string LastName, string MiddleName, string SSN );
// Instance of the delegate
private AddEventCallback m_addEventCallback;
private Employees m_employees;
private int m_lengthQueue;
private string[, ] m_msgQueue =
{
{"Timothy", "Arthur", "Tucker", "555-55-5555"},
{"Sally", "Bess", "Jones", "666-66-6666" },
{"Jeff", "Michael", "Simms", "777-77-7777"},
{"Janice", "Anne", "Best", "888-88-8888" }
};
public EmployeeQueueMonitor( Employees employees )
{
m_employees = employees;
m_lengthQueue = 4;
// Create an instace of the delegate and register the
// addEmployee method of this class as a callback.
m_addEventCallback = new AddEventCallback(
this.addEmployee );
}
// Drain the queue.
public void start()
{
if ( m_employees == null )
return;
http://www.syngress.com
Figure 2.7 Continued
Continued.Introducing C# Programming • Chapter 2 73
for ( int i = 0; i < m_lengthQueue; i++ )
{
string FirstName = m_msgQueue[i,0];
string MiddleName = m_msgQueue[i,1];
string LastName = m_msgQueue[i,2];
string SSN = m_msgQueue[i,3];
// Invoke the callback registered with the delegate
Console.WriteLine( "Invoking delegate" );
m_addEventCallback( FirstName, LastName, MiddleName,
SSN );
}
}
public void stop()
{
// In a real communications program you would shut down
// gracefully.
}
// Called by the delegate when a message to add an employee
// is read from the message queue.
public void addEmployee( string FirstName, string MiddleName,
string LastName, string SSN )
{
Console.WriteLine( "In delegate, adding employee\r\n" );
int index = m_employees.Length;
m_employees[index] = new Employee ( FirstName, MiddleName,
LastName, SSN );
}
}
http://www.syngress.com
Figure 2.7 Continued.74 Chapter 2 • Introducing C# Programming
Single Cast
The source code in the previous section is an example of a single cast delegate. A
single cast delegate invokes only one callback method. Let’s examine our previous
sample to see this.
The EmployeeQueueMonitor class simulates a message queue. It contains a static
array that holds the current messages. At the top of EmployeeQueueMonitor are the
following lines:
public delegate void AddEventCallback( string FirstName,
string LastName, string MiddleName, string SSN );
private AddEventCallback m_addEventCallback;
The first statement defines a delegate and the parameters an object instance
of the delegate takes. In this case, we callback to a method that takes first name,
last name, middle name, and SSN. We do this whenever a request to add a new
employee appears in the message queue.
The second statement declares a member variable to hold our delegate. It is
initially set to null. A new object instance must be created prior to making
method calls through the delegate. An object instance is instantiated in the con-structor
of EmployeeQueueMonitor.
m_addEventCallback = new AddEventCallback( this.addEmployee );
This statement creates a new object instance of the delegate. The delegate
takes as an argument the method to call when the delegate is invoked. In this
case, whenever the delegate is invoked, the method that will execute is
EmployeeQueueMonitor.addEmployee.
In the start method of EmployeeQueueMonitor is the following code:
for ( int i = 0; i < m_lengthQueue; i++ )
{
string FirstName = m_msgQueue[i,0];
string MiddleName = m_msgQueue[i,1];
string LastName = m_msgQueue[i,2];
string SSN = m_msgQueue[i,3];
// Invoke the callback registered with the delegate
Console.WriteLine( "Invoking delegate" );
http://www.syngress.com.Introducing C# Programming • Chapter 2 75
m_addEventCallback( FirstName, LastName, MiddleName, SSN );
}
This code simulates draining the message queue of any waiting messages.The
callback function is invoked by treating the m_addEventCallback member variable
as if it were a method call passing it our four parameters. Note that you do not
specify the callback itself when making the call.The delegate maintains the
address of the callback internally and therefore knows the method to call.The
following example shows what not to do:
// Incorrect
m_addEventCallback.addEmployee( FirstName, LastName, MiddleName, SSN );
Multicast
The true power of delegates becomes apparent when discussing multicast dele-gates.
Let’s extend our previous example a bit further. Because background pro-cesses
do not usually have a user interface for human interaction, they typically
log incoming events for later review. Let’s add a second callback to our sample to
log incoming add employee requests.The relevant snippets of code are shown in
Figure 2.8.The full source code is for this sample is on the CD in the file
Multicasting.cs.
Figure 2.8 Relevant Portions of the Multicasting.cs Program Listing
class EmployeeQueueMonitor
{
// Delegate signature for add employee event callback
public delegate void AddEventCallback( string FirstName,
string LastName, string MiddleName, string SSN );
// Instance of the delegate
private AddEventCallback m_addEventCallback;
private EmployeeQueueLogger m_logger;
public EmployeeQueueMonitor( Employees employees )
{
http://www.syngress.com
Continued.76 Chapter 2 • Introducing C# Programming
m_employees = employees;
m_lengthQueue = 4;
m_logger = new EmployeeQueueLogger( "log.txt" );
// Register the methods that the delegate will invoke when an
// add employee message is read from the message queue
m_addEventCallback =
new AddEventCallback( this.addEmployee );
m_addEventCallback +=
new AddEventCallback( m_logger.logAddRequest );
}
// Drain the queue.
public void start()
{
if ( m_employees == null )
return;
for ( int i = 0; i < m_lengthQueue; i++ )
{
string FirstName = m_msgQueue[i,0];
string MiddleName = m_msgQueue[i,1];
string LastName = m_msgQueue[i,2];
string SSN = m_msgQueue[i,3];
Console.WriteLine( "Invoking delegate" );
// Invoke the delegate passing the data associated with
// adding a new employee resulting in the subscribed
// callbacks methods being executed, namely
// Employees.this.addEmployee()
http://www.syngress.com
Figure 2.8 Continued
Continued.Introducing C# Programming • Chapter 2 77
// and EmployeeQueueLogger.logAddRequest()
m_addEventCallback( FirstName, LastName, MiddleName,
SSN );
}
}
// Called by delegate whenever a new add employee message
// appears in the message queue. Notice the signature matches
// that requried by AddEventCallback
public void addEmployee( string FirstName, string MiddleName,
string LastName, string SSN )
{
Console.WriteLine( "In delegate, adding employee\r\n" );
int index = m_employees.Length;
m_employees[index] = new Employee ( FirstName, MiddleName,
LastName, SSN );
}
}
/// <summary>
/// Writes add employee events to a log file.
/// </summary>
class EmployeeQueueLogger
{
string m_fileName;
public EmployeeQueueLogger( string fileName )
{
m_fileName = fileName;
}
// Called by delegate whenever a new add employee message
http://www.syngress.com

时间: 2024-10-30 15:57:10

Using Delegates and Events 1 (来自一本49美元/817页2002年的书《C#.net web developers guide》)的相关文章

Using Delegates and Events 2 (来自一本49美元/817页2002年的书《C#.net web developers guide》)

guid|web Figure 2.8 ContinuedContinued.78 Chapter 2 • Introducing C# Programming// appears in the message queue. Notice the signature matches// that requried by AddEventCallbackpublic void logAddRequest( string FirstName, string LastName,string Middl

请教:朋友跟我想写一本关于JAVA虚拟机详解方面的书。

问题描述 朋友跟我想写一本关于JAVA虚拟机详解方面的书.书的内容主要包括JVM的原理,JVM源码分析等方面的问题.书本身内容清晰,层次很分明,也很通俗易懂.目前书已经写了一半,大概6章的内容..不知道怎么联系出版社,如果出版以后销路会如何.也不知道有没有多少读者会关注JAVA虚拟机方面的知识..大家给点意见,或者渠道..谢谢. 解决方案 解决方案二:顶,一直有个小理想,自己写本jvm分析的书,不过未能实现.感觉这种书很小众.jvm原理的书还可以,但代码分析的未必对大部分java程序员有多大价值

AT&amp;T将iPhone 3GS两年合约价下调至49美元

美国电话电报公司AT&T于6日宣布,该公司将于当地时间7日起以49美元的两年合约价格销售iPhone 3GS.并称,这一政策适用于通过该公司和http://www.aliyun.com/zixun/aggregation/7176.html">苹果销售的iPhone 3GS. 2009 年6月,苹果公司第三代iPhone-"iPhone3GS"正式发售,去年7月份,苹果发售iPhone 4,iPhone 4可以运行与iPhone 3GS相同的iOS4软件.自iP

AT&T在美国出售3G版iPhone翻新机49美元

AT&T出售的翻新机信息 北京时间7月26日中午消息,据国外媒体报道,AT&T周五晚间通过Twitter宣布,正在以最低49美元的价格发售iPhone翻新机. 在该公司网站上,8GB版的iPhone 3G翻新机正在以这个价格出售. iPhone 3GS目前正在美国大多数苹果商店中上架销售,因此AT&T此举可能是为了清理旧款iPhone的库存.由于49美元的iPhone对大多数人来说确实难以拒绝,AT&T或许很快就能清空库存.(逸飞)

威盛公布49美元PC 运行定制版Android

[搜狐IT消息]北京时间5月23日消息,据国外媒体报道,芯片厂商威盛周二公布了一款售价仅为49美元的PC,运行定制版Android操作系统.威盛49美元PC基本上就是一块主板,外加一个机壳.威盛在其网站上公布的消息显示,这款产品将于7月上市发售.用户需要单独购买键盘.鼠标和显示器.威盛对49美元PC的定位是,取代Windows桌面机运行基本的互联网和办公应用.威盛在其网站上称,"价格高.处理能力超强的处理器,大块头的软件已经无足轻重.我们将把PC的能耗降低到令节能灯嫉妒的水平."威盛4

AT&T销售49美元翻新iPhone3G手机

7月28日消息,AT&T日前宣布,将会特价销售翻新的iPhone3G手机,该款黑色外壳.8GB容量的翻新机的售价仅为49美元,然而该批产品数量有限,售完为止,这样的价格相当于同款新机价格的一半.此外,AT&T还以99美元的价格销售16GB的翻新iPhone,外壳颜色有黑色和白色两款可选. 据国外媒体报道,业内分析人士指出,该机适合那些对iPhone的3G功能感兴趣,而又不很在意摄像效果的用户,但是用户依然需要签订2年的服务合同. AT&T网站表示,翻新手机是指那些30天试用期内退回

携程股价跌5.02美元至39.49美元,跌幅达11.27%

查看最新行情 携程旅游网周四早盘大跌超11% 1月9日晚间消息,携程旅游网(Nasdaq: CTRP )今日开盘大跌,最大跌幅超13%,截至北京时间23:15,携程股价跌5.02美元至39.49美元,跌幅达11.27%. 近几日携程股价持续下跌,相比近一个月最高点52.55美元的价格已下跌超过20%.

苹果将8GB版iPhone 3GS价格下调至49美元

苹果已经悄悄将与AT&T签2年合同的8GB版iPhone 3GS的价格下降至49美元,这与上周运营商AT&T所发布的新价格一致. 虽然8GB iPhone 3GS现在的价格从原先的99美元下降到49美元,但苹果未公开宣布降价行动. 上周AT&T也将该款产品下调至49美元,并明确表示,苹果有自己的http://www.aliyun.com/zixun/aggregation/18505.html">销售渠道如零售和在线店,iPhone 3GS的售价由苹果自己决定,这意

Auriga初评网易为买入目标价49美元

北京时间周四晚间消息,券商Auriga U.S.A将网易公司(NTES)的初始评级确定为"买入",并将其目标股价确定为49美元.