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

guid|web

Figure 2.8 Continued
Continued.78 Chapter 2 • Introducing C# Programming
// appears in the message queue. Notice the signature matches
// that requried by AddEventCallback
public void logAddRequest( string FirstName, string LastName,
string MiddleName, string SSN )
{
string name = FirstName + " " + MiddleName + " " + LastName;
FileStream stream = new FileStream( m_fileName,
FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter( stream );
writer.BaseStream.Seek( 0, SeekOrigin.End );
writer.Write("{0} {1} \n", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
writer.Write( "Adding employee - Name: {0}, SSN: {1}",
name, SSN );
writer.Write("\n------------------------------------\n\n");
writer.Flush();
writer.Close();
}
}
A new class, EmployeeQueueLogger, has been added. It has a method
logAddRequest, which logs requests to add employees to a log file. The important
thing to note is that the logAddRequest method has a signature that matches the
AddEventCallback delegate signature. An instance of the logger is created in the
constructor of EmployeeQueueMonitor. The code that wires up the delegates is also
in the constructor and is shown here:
m_logger = new EmployeeQueueLogger( "log.txt" );
m_addEventCallback = new AddEventCallback( this.addEmployee );
m_addEventCallback += new AddEventCallback(
m_logger.logAddRequest );
http://www.syngress.com
Figure 2.8 Continued.Introducing C# Programming • Chapter 2 79
First, a new logger instance is created. Next, the delegate is initialized with a
first callback function to the addEmployee method of EmployeeQueueMonitor.
Finally, a second callback is added to the delegate, which will invoke the
logAddRequest of the EmployeeQueueLogger class. Notice that the plus sign is used
to add the second callback to the delegate. The plus sign (addition operator) has
been overloaded in the System.Delegate class of the .NET Framework to call the
Combine method of that class.The Combine method adds the callback to the list of
methods the delegate maintains.The minus sign (subtraction operator) is also
overloaded to call the Remove method, which removes a callback from the list of
methods the delegate maintains.The rest of the source code remains unchanged.
When the delegate is invoked in the start method of EmployeeQueueMonitor, both
EmployeeQueueMonitor.addEmployee and EmployeeQueueLogger.logAddRequest are
executed.
Events
The event model is often referred to as the publish/subscribe model or the listener
pattern. The idea behind the event model is that a class publishes the events that it
can raise. Consumers of the class object subscribe to the events they are interested
in.When the event occurs, the object that monitors the event notifies all sub-scribers
that the event has been raised.The subscribers then take some action.
The event model is often used in GUI programs. Handlers are set up for
common events, such as pressing a button.When the button press event occurs,
all subscribers registered for the button press event are invoked.The .NET
Framework uses the event model and in particular the System.Event delegate for
Windows Forms–based applications.
The .NET Framework supplies a built in delegate of type System.Event. The
idea of events in the .NET Framework is to supply a single signature for the del-egate
regardless of the data that is passed to the subscribed callback. One of the
arguments for the Event delegate is an object derived from the .NET Framework
class System.EventArgs, which contains the data the callback needs.You declare a
class derived from System.EventArgs with the data your callback needs.When the
event takes place, you instantiate your derived EventArgs object and invoke the
event. Callback functions subscribed to the event are called passing the object
derived from EventArgs. Changes to the multicast delegate code sample that
implement events are shown in Figure 2.9.The full source code for this sample is
on the CD in the file Events.cs.
http://www.syngress.com.80 Chapter 2 • Introducing C# Programming
Figure 2.9 Relevant Portions of the Events.cs Program Listing
/// <summary>
/// Defines the data that will be passed from the event delegate to
/// the callback method when the event is raised
/// </summary>
class AddEmployeEventArgs : EventArgs
{
string m_FirstName;
string m_LastName;
string m_MiddleName;
string m_SSN;
public AddEmployeEventArgs( string FirstName,
string LastName, string MiddleName, string SSN )
{
m_FirstName = FirstName;
m_LastName = LastName;
m_MiddleName = MiddleName;
m_SSN = SSN;
}
// Event argument properties contain the data to pass to the
// callback methods subscribed to the event.
public string FirstName { get { return m_FirstName; } }
public string LastName { get { return m_LastName; } }
public string MiddleName {get { return m_MiddleName; } }
public string SSN { get { return m_SSN; } }
}
/// <summary>
/// Simulates monitoring a message queue. When a message appears
/// the event is raised and methods subscribed to the event
// are invoked.
/// </summary>
http://www.syngress.com
Continued.Introducing C# Programming • Chapter 2 81
class EmployeeQueueMonitor
{
// Event signature for AddEmployeeEvent
public delegate void AddEmployeeEvent( object sender,
AddEmployeEventArgs e );
// Instance of the AddEmployeeEvent
public event AddEmployeeEvent OnAddEmployee;
private EmployeeQueueLogger m_logger;
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;
m_logger = new EmployeeQueueLogger( "log.txt" );
// Register the methods that the Event will invoke when an add
// employee message is read from the message queue
OnAddEmployee +=
new AddEmployeeEvent( this.addEmployee );
http://www.syngress.com
Figure 2.9 Continued
Continued.82 Chapter 2 • Introducing C# Programming
OnAddEmployee +=
new AddEmployeeEvent( m_logger.logAddRequest );
}
// Drain the queue.
public void start()
{
if ( m_employees == null )
return;
for ( int i = 0; i < m_lengthQueue; i++ )
{
// Pop an add employee request off the queue
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" );
// Create the event arguments to pass to the methods
// subscribed to the event and then invoke event resulting
// in the callbacks methods being executed, namely
// Employees.this.addEmployee() and
// EmployeeQueueLogger.logAddRequest()
AddEmployeEventArgs args = new AddEmployeEventArgs( FirstName,
LastName, MiddleName, SSN );
OnAddEmployee( this, args );
}
}
public void stop()
{
http://www.syngress.com
Figure 2.9 Continued
Continued.Introducing C# Programming • Chapter 2 83
// In a real communications program you would shut down
// gracefully.
}
// Called by event whenever a new add employee message appears
// in the message queue. Notice the signature matches that required
// by System.Event
public void addEmployee( object sender, AddEmployeEventArgs e )
{
Console.WriteLine( "In delegate, adding employee\r\n" );
int index = m_employees.Length;
m_employees[index] = new Employee ( e.FirstName, e.MiddleName,
e.LastName, e.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 event whenever a new add employee message appears
// in the message queue. Notice the signature matches that required
// by System.Event
public void logAddRequest( object sender, AddEmployeEventArgs e )
http://www.syngress.com
Figure 2.9 Continued
Continued.84 Chapter 2 • Introducing C# Programming
{
string name = e.FirstName + " " + e.MiddleName + " " +
e.LastName;
FileStream stream = new FileStream( m_fileName,
FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter( stream );
writer.BaseStream.Seek( 0, SeekOrigin.End );
writer.Write("{0} {1} \n", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
writer.Write( "Adding employee - Name: {0}, SSN: {1}",
name, e.SSN );
writer.Write("\n------------------------------------\n\n");
writer.Flush();
writer.Close();
}
}
A new class, AddEmployeEventArgs, has been added. It contains the informa-tion
that will be passed to callback methods subscribed to the event. Notice the
data members of the AddEmployeEventArgs class are the same as the signature for
the AddEventCallback delegate in our previous sample. Instead of invoking the
callback with individual arguments, when using events, you pass a class object,
which contains the arguments instead.
Just as with the delegates samples, we declare the signature and create a
member variable for the delegate in EmployeeQueueMonitor class. The only differ-ence
is that the signature matches the signature necessary for events.The first
parameter is the object that raised the event, and the second is the object instance
that contains the arguments passed to subscribed callback methods.This is shown
here:
public delegate void AddEmployeeEvent( object sender,
http://www.syngress.com
Figure 2.9 Continued.Introducing C# Programming • Chapter 2 85
AddEmployeEventArgs e );
public event AddEmployeeEvent OnAddEmployee;
In the constructor of the class, we subscribe the callback methods to the
event as shown here:
OnAddEmployee +=
new AddEmployeeEvent( this.addEmployee );
OnAddEmployee +=
new AddEmployeeEvent( m_logger.logAddRequest );
The callback methods have the correct signature for event callbacks. Here are
the callback method’s signatures:
public void addEmployee( object sender, AddEmployeEventArgs e )
public void logAddRequest( object sender, AddEmployeEventArgs e )
When an add employee message is popped off the queue in the start method
of EmployeeQueueMonitor, an instance of the AddEmployeeEventArgs is created and
the event is invoked. Here is the code that accomplishes this:
AddEmployeEventArgs args = new AddEmployeEventArgs( FirstName,
LastName, MiddleName, SSN );
OnAddEmployee( this, args );
As you can see, using events instead of delegates is really just a syntactic dif-ference.
The code is nearly identical.The main benefit is that you don’t have a
different delegate signature for every delegate you create based on the data that is
passed to subscribed callbacks. Instead, the standard event delegate signature will
suffice.

时间: 2025-01-03 07:55:05

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

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

guid|web Using Delegates and EventsIf you are familiar with Windows programming, you've most likely dealt withcallbacks. Callbacks are method calls that are executed when some event happenshttp://www.syngress.com.70 Chapter 2 • Introducing C# Program

请教:朋友跟我想写一本关于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美元.