Tải bản đầy đủ (.pdf) (48 trang)

Tài liệu Module 8: Delegates and Events docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (975.87 KB, 48 trang )








Contents
Overview 1
Delegates 2
Multicast Delegates 12
Events 21
When to Use Delegates, Events, and
Interfaces 31
Lab 8: Creating a Simple Chat Server 32
Review 42

Module 8:
Delegates and Events


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.


Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2001-2002 Microsoft Corporation. All rights reserved.

Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint,
Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 8: Delegates and Events iii


Instructor Notes
After completing this module, students will be able to:
!
Use the delegate class to create type-safe callback functions and event-
handling methods.
!
Use the event keyword to simplify and improve the implementation of a
class that raises events.
!
Implement events that conform to the Microsoft

®
.NET Framework
guidelines.

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the Microsoft PowerPoint
®
file 2349B_08.ppt.
Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Practice the demonstrations.
!
Complete the lab.

Presentation:
75 Minutes

Lab:
75 Minutes
iv Module 8: Delegates and Events


Demonstrations
This section provides demonstration procedures that will not fit in the margin

notes or are not appropriate for the student notes.
Using Delegates
In this demonstration, you will use Microsoft

Visual Studio
®
.NET to run code
in which a delegate to a light object’s method is passed to a switch object.
When the switch object’s state changes, the switch object calls the light
object’s method and passes its new state.
The code for this demonstration is provided in the student notes. The
demonstration files are located in <install folder>\Democode\Mod08\
Demo08.1\Using Delegates.
Multicast Delegates
In this demonstration, you will show students how to add and remove methods
from the invocation list of multicast delegates by using the plus operator (+)
and the minus operator (-).
The code for this demonstration is provided in the student notes. The
demonstration files are located in <install folder>\Democode\Mod08\
Demo08.2\MULTICAST DELEGATES.
Module Strategy
Use the following strategy to present this module:
!
Delegates
Use the Delegate Scenario to help students to visualize and comprehend the
concept of delegates. Some students may question the validity of this
scenario. In the real world, a house would never be rewired dynamically, but
you can explain that software programs often need to rebind dynamically.
!
Multicast Delegates

Contrast typical multicast delegate use with that of the single delegate
example by using the common scenario of a switch that controls two light
bulbs. Explain how to create and invoke multicast delegates and show how
to use the + and – operators in C# to add and remove methods from the
invocation list of multicast delegates.
!
Events
Use the Event Scenario to help students to visualize and comprehend the
concept of events. Emphasize that events are an important building block
for creating classes that can be reused in many different programs, and that
delegates are particularly suited for event handling. Explain how to declare,
connect to, and raise an event.
Introduce the .NET Framework guidelines for delegates and events.
!
When to Use Delegates, Events, and Interfaces
Contrast and compare the specific usage characteristics of delegates,
interfaces, and events for providing callback functionality in particular
situations.

Module 8: Delegates and Events 1


Overview
!
Delegates
!
Multicast Delegates
!
Events
!

When to Use Delegates, Events, and Interfaces

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In the Microsoft
®
.NET Framework, delegates are the object-oriented
equivalents of function pointers. However, unlike function pointers, delegates
are type-safe and secure. The common language runtime supports the use of
delegates in callback and event-handling scenarios.
An event is raised by an object or event source in response to an action
performed by a user or some sort of program logic. The event receiver must
then respond to the raised event and perform an action. The event keyword lets
you specify delegates that will be called upon the occurrence of an event.
After completing this module, you will be able to:
!
Use the delegate class to create type-safe callback functions and event-
handling methods.
!
Use the event keyword to simplify and improve the implementation of a
class that raises events.
!
Implement events that conform to the .NET Framework guidelines.

Topic Objective
To provide an overview of
the module topics and

objectives.
Lead-in
Delegates are the object-
oriented equivalents of
function pointers.
2 Module 8: Delegates and Events


"
""
" Delegates
!
Delegate Scenario
!
Declaring a Delegate
!
Instantiating a Delegate
!
Calling a Delegate

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You can use delegates to encapsulate a reference to a method inside a delegate
object. Because delegates are type-safe, secure, managed objects, they offer all
of the advantages of pointers without any of the disadvantages of pointers. For
example, delegates will always point to a valid object and cannot corrupt the
memory of other objects.

Topic Objective
To provide an overview of
the topics in this section.
Lead-in
In this section, you will learn
about how delegates are
used in the .NET
Framework.
Module 8: Delegates and Events 3


Delegate Scenario
1 - Change in
switch position
invokes switch’s
OnFlip method
2 - OnFlip Method
invokes delegate
3 - Delegate invokes light’s
OnFlipCallback method
4 - OnFlipCallback method
changes light’s state
OnFlip method
Switch Object
OnFlipCallback
method
Light Object
Delegate object
Delegate object
OnFlip method

Switch Object

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
This scenario of a switch that controls a light illustrates one use of delegates.
The switch object models an electric switch, and the light object models an
electric light. The delegate object encapsulates a reference to a light object’s
OnFlipCallback method.
The switch object code could be written without a delegate by referring directly
to the specific light object’s method. However, this approach does not offer the
flexibility to dynamically connect, disconnect, and reconnect various light
object methods to the switch object. You can use a delegate object that
connects the switch object and the light object to achieve this flexibility.
In real life, the preceding scenario would probably not occur as described.
While a house would never be rewired dynamically, software programs often
need to dynamically rebind.
When the switch is flipped in the light switch scenario shown in the slide:
1. The switch object’s OnFlip method is invoked.
2. The OnFlip method invokes the delegate object.
3. The delegate object invokes the light object’s OnFlipCallback method.
4. The OnFlipCallback method changes the state of the light.


Topic Objective
To illustrate one use of
delegates through the
scenario of a switch and a

light bulb.
Lead-in
This scenario of a switch
that controls a light
illustrates one use of
delegates.
To run the build slide, click
through the lower-left button
on the slide.
For Your Information
Stress that this scenario
reflects a common scenario
to which everyone can
relate. While you may not
use the same light switch to
turn different lights on and
off at different times, this
scenario helps you to
visualize and comprehend
the concepts behind
delegates.
Delivery Tip
You should briefly preview
the Demonstration: Using
Delegates to provide
students with an overview of
the code that can be used to
implement this scenario.
Defer discussion of delegate
specific code until after the

following topics are covered.
4 Module 8: Delegates and Events


Declaring a Delegate
!
A Delegate Declaration Defines a Type That
Encapsulates a Method with a Particular Set of
Arguments and Return Type
// declares a delegate for a method that takes a single
// argument of type string and has a void return type
delegate void MyDelegate1(string s);
// declares a delegate for a method that takes a single
// argument of type string and has a void return type
delegate void MyDelegate1(string s);

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
A delegate declaration defines a type that encapsulates a method with a
particular set of arguments and return type. The delegate declaration is
sufficient to define a delegate class whose actual implementation is provided by
the common language runtime.
The following example shows how to declare a delegate for a method that takes
a single argument of type string and has a void return type:
delegate void MyDelegate1(string s);

Topic Objective

To explain how to declare a
delegate.
Lead-in
A delegate declaration
defines a type that
encapsulates a method with
a particular set of arguments
and return type.
For Your Information
The details of how the
common language runtime
creates delegates are
presented later in this
module.
Module 8: Delegates and Events 5


Instantiating a Delegate
!
A Delegate Object Is Created with the new Operator
!
Delegate Objects Are Immutable
// instantiating a delegate to a static method Hello
// in the class MyClass
MyDelegate1 a = new MyDelegate1(MyClass.Hello);
// instantiating a delegate to an instance method
// AMethod in object p
MyClass p = new MyClass();
MyDelegate1 b = new MyDelegate1(p.AMethod);
// instantiating a delegate to a static method Hello

// in the class MyClass
MyDelegate1 a = new MyDelegate1(MyClass.Hello);
// instantiating a delegate to an instance method
// AMethod in object p
MyClass p = new MyClass();
MyDelegate1 b = new MyDelegate1(p.AMethod);

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
After you have declared a delegate type, you can create a delegate object and
associate it with a particular method. This topic explains the code used to
instantiate delegates.
Creating a New Delegate Object
Like all objects, a new delegate object is created with the new operator. When
creating a delegate, however, the argument passed to the new operator is
special: it is written like a method call, but without the arguments to the
method. After a delegate is created, the method to which it is associated never
changes: delegate objects are immutable.
When referencing an object, an interesting and useful feature of a delegate is
that the delegate does not know or care about the class of the object that it
references. It can reference any object as long as the method’s signature
matches the delegate’s signature.
A delegate can reference static or instance methods. When referencing instance
methods, the delegate stores not only a reference to the method’s entry point,
but also a reference to the object instance on which the method is invoked.
Topic Objective
To explain how to instantiate

delegates.
Lead-in
After you have declared a
delegate type, you can
create a delegate object and
associate it with a particular
method.
Delivery Tip
To place the delegate
instantiation code in a fuller
context, refer to the
following code example.
6 Module 8: Delegates and Events


The following example shows how to declare a delegate named MyDelegate1.
The code illustrates how this delegate can be instantiated to a static or an
instance method. The signature of the method and MyDelegate1 must match;
the method must have a void return and take a single argument of type string.
delegate void MyDelegate1(string s);

public class MyClass
{
public static void Hello(string s) {
//
}
public void AMethod(string s) {
//
}
}



// instantiating a delegate to a static method
MyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to object p's AMethod method
MyClass p = new MyClass();
MyDelegate1 b = new MyDelegate1(p.AMethod);

Module 8: Delegates and Events 7


Calling a Delegate
!
Use a Statement Containing:
#
The name of the delegate object
#
Followed by the parenthesized arguments to be passed
to the delegate
// given the previous delegate declaration and
// instantiation, the following invokes MyClass'
// static method Hello with the parameter "World"
a("World");
// given the previous delegate declaration and
// instantiation, the following invokes MyClass'
// static method Hello with the parameter "World"
a("World");

*****************************

ILLEGAL FOR NON
-
TRAINER USE
******************************
After a delegate object is created, it can be passed to other code that will call the
delegate. For example, a server object may provide a method that a client
object calls to register a callback method for a specific event. The server will
invoke this callback method when that event occurs. Typically, the client
instantiates a delegate that refers to its callback method. The client passes the
callback delegate object as a parameter.
You can call a delegate object by using the name of the delegate, followed by
the parenthesized arguments to be passed to the delegate. For example, using
the declaration and instantiations of delegates a and b shown in the previous
slide, the following lines invoke the static Hello method of the class MyClass
and the AMethod of the MyClass object p with the argument
"
World
"
:
a(
"
World
"
);
b(
"
World
"
);


Topic Objective
To explain how to call
delegates.
Lead-in
After a delegate is created,
it can be passed to other
code that will call the
delegate.
For Your Information
Refer to the previous slide
on delegate declaration and
instantiations.
8 Module 8: Delegates and Events


Demonstration: Using Delegates

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this demonstration, you will use Microsoft

Visual Studio
®
.NET to run code
in which a delegate to a light object’s method is passed to a switch object.
When the switch object’s state changes, the switch object calls the light
object’s method and passes its new state.

Topic Objective
To demonstrate using a
callback delegate.
Lead-in
In this demonstration, you
will use Microsoft

Visual
Studio .NET to run code in
which a delegate to a
light

object’s method is passed to
a
switch
object. When the
switch
object’s state
changes, the
switch
object
calls the
light
object’s
method and passes its new
state.
Delivery Tip
Use Visual Studio .NET to
run the following code. Set
breakpoints or single step to

illustrate the sequence of
events.
Module 8: Delegates and Events 9


using System;

namespace SwitchAndLight
{
public enum SwitchPosition {Up, Down};

delegate void SwitchFlipped(SwitchPosition switchState);

class Light
{
private string name;

public Light(string s)
{
name = s;
}

public void OnFlipCallback(SwitchPosition switchState)
{
if (switchState == SwitchPosition.Up)
{
Console.WriteLine(" {0} light is on",name);
}
else
{

Console.WriteLine(" {0} light is off",name);
}
}
}

class Switch
{
private SwitchPosition switchState =
SwitchPosition.Down;
private SwitchFlipped switchFlippedHandler = null;

public void ConnectToLight(SwitchFlipped lightHandler)
{
switchFlippedHandler = lightHandler;
}

public SwitchPosition SwitchState
{
get {return switchState;}
}

(Code continued on the following page.)
For Your Information
As noted in C# Language-
Specific Syntax in this
module, delegate types with
a
void
return value in C#
cause the compiler to derive

the delegate class from the
MulticastDelegate
class.
Therefore, the IL for this
delegate demonstration
code will show the
SwitchFlipped
delegate
inheriting from the
System.MulticastDelegate

class.
10 Module 8: Delegates and Events


public void OnFlip()
{
if (switchState == SwitchPosition.Down)
{
switchState = SwitchPosition.Up;
}
else
{
switchState = SwitchPosition.Down;
}
if (switchFlippedHandler != null)
{
switchFlippedHandler(switchState);
}
}

}

class TheApp
{
static void OnFlip(Switch aSwitch)
{
Console.WriteLine(
"Before flipping, the switch is: {0}",
aSwitch.SwitchState);
Console.WriteLine("Flipping switch ");
aSwitch.OnFlip();
Console.WriteLine(
"After flipping, the switch is: {0}\n\n",
aSwitch.SwitchState);
}

static void Main(string[] args)
{
Switch s = new Switch();
Light light1 = new Light("bathroom");
Light light2 = new Light("bedroom");

// connect switch and bathroom light by passing a
// delegate to the bathroom light's
// OnFlipCallback method to s
s.ConnectToLight(new
SwitchFlipped(light1.OnFlipCallback));
OnFlip(s);
OnFlip(s);


// connect switch and bedroom light by passing a
// delegate to the bedroom's light's
// OnFlipCallback method to s
s.ConnectToLight(new
SwitchFlipped(light2.OnFlipCallback));
OnFlip(s);
OnFlip(s);

}
}
}
Module 8: Delegates and Events 11


This code generates the following output:
Before flipping, the switch is: Down
Flipping switch
bathroom light is on
After flipping, the switch is: Up


Before flipping, the switch is: Up
Flipping switch
bathroom light is off
After flipping, the switch is: Down


Before flipping, the switch is: Down
Flipping switch
bedroom light is on

After flipping, the switch is: Up


Before flipping, the switch is: Up
Flipping switch
bedroom light is off
After flipping, the switch is: Down

12 Module 8: Delegates and Events


"
""
"

Multicast Delegates
!
Multicast Delegate Scenario
!
Single vs. Multicast Delegates
!
Creating and Invoking Multicast Delegates
!
C# Language-Specific Syntax
!
Delegate Details

*****************************
ILLEGAL FOR NON
-

TRAINER USE
******************************
If you change the state in one object, you may need to broadcast that change to
multiple objects. You can use multicast delegate objects to provide this
functionality; they can be composed together so that a single invocation invokes
all of their methods, just as a single light switch can turn on or off all lights
connected to that switch.

Topic Objective
To provide an overview of
the topics in this section.
Lead-in
If you change the state in
one object, you may need to
broadcast that change to
multiple objects.
For Your Information
As noted in the C#
Language-Specific Syntax in
this module, delegate types
with a
void
return value in
C# cause the compiler to
derive the delegate class
from the
MulticastDelegate

class.
Module 8: Delegates and Events 13



Multicast Delegate Scenario
2 - OnFlip method
invokes multicast
delegate1
4 - OnFlipCallback method
changes light1’s state
3 - delegate1 invokes
light1’s OnFlipCallback
7 - OnFlipCallback
method changes
light2’s state
6 - delegate2 invokes
light2’s OnFlipCallback
OnFlip method
Switch Object
OnFlipCallback
method
Light1 Object
OnFlipCallback
method
Light2 Object
Multicast delegate1 object
Multicast delegate1 object
Multicast delegate2 object
Multicast delegate2 object
Invocation list
5 - delegate2
is invoked

1 - Change in
switch position
invokes switch’s
OnFlip method
OnFlip method
Switch Object

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In the light scenario, multicast delegate1 refers to the light1 object’s
OnFlipCallback method, and multicast delegate2 refers to the light2 object’s
OnFlipCallback method. Their composition logically represents an invocation
list, a list of methods that are executed when the delegate is invoked. In this
case, the invocation list consists of these two methods.
In the light switch scenario shown in the slide, the multicast delegate objects
encapsulate references to two objects and two methods. When the switch is
flipped:
1. The switch object’s OnFlip method is invoked.
2. The OnFlip method invokes the multicast delegate1 object.
3. The multicast delegate1 object first invokes the light1 object’s
OnFlipCallback method.
4. The light1 object’s OnFlipCallback method changes the state of the light1
object.
5. The multicast delegate1 object next invokes the multicast delegate2
object.
6. The multicast delegate2 object invokes the light2 object’s
OnFlipCallback method.

7. The light2 object’s OnFlipCallback method changes the state of the light2
object.

You can compose additional multicast delegates to allow the switch to control
additional lights.
Topic Objective
To illustrate the typical
multicast delegate use by
using the common scenario
of a switch that controls two
light bulbs.
Lead-in
The following scenario of a
switch that controls two
lights illustrates the use of
multicast delegates.
To run the build slide, click
through the lower-left button
on the slide.
The following scenario of a
switch that controls two
lights illustrates the use of
multicast delegates. The
switch
object models the
light switch, and the two
light
objects model the two
electric lights. To


provide
the capability to dynamically
connect, disconnect, and
reconnect
light
object
methods to the
switch

object, the
switch
object is
dynamically connected to
the
light
objects by
instantiating and composing
two multicast delegate
objects.
14 Module 8: Delegates and Events


Single vs. Multicast Delegates
!
All Delegates Have an Invocation List of Methods That Are
Executed When Their Invoke Method is Called
!
Single-Cast Delegates: Derived Directly From
System.MulticastDelegate
#

Invocation list contains only one method
!
Multicast Delegates: Derived from System.MulticastDelegate
#
Invocation list may contain multiple methods
#
Multicast delegates contain two static methods to add and remove
references from invocation list: Combine and Remove
!
Use GetInvocationList to Obtain an Invocation List as an Array of
Delegate References
!
Use a Delegate’s Target and Method Properties to Determine:
#
Which object will receive the callback
#
Which method will be called

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When delegate declarations are compiled, the compiler, in effect, generates a
new class. The new delegate class derives from the System.MulticastDelegate
class that is provided by the .NET Framework.
All delegates have an invocation list, or linked list of delegates that are
executed when the invoke method is called. A delegate that derives from the
MulticastDelegate class may contain an invocation list with multiple delegates.
The MulticastDelegate class contains two static methods to add and remove

method references from an invocation list: Combine and Remove.
Combine is declared as follows:
public static Delegate Combine(
Delegate a,
Delegate b);

The method returns a new multicast Delegate object with an invocation list that
concatenates the invocation lists of a and b in that order.
Remove is declared as follows:
public static Delegate Remove(
Delegate source,
Delegate value);

The method returns a new Delegate object with an invocation list formed by
taking the invocation list of source and removing the last occurrence of value,
if value is found in the invocation list of source. If value is null or if value is
not found, then source is returned.
You can use the method GetInvocationList to obtain the invocation list as an
array of delegate references. You can also use the delegate’s Target and
Method properties to determine which object is to receive the callback and
which method is to be called. In the case of a static method, Target is null.
Topic Objective
To explain the difference
between single-cast and
multicast delegates.
Lead-in
When delegate declarations
are compiled, the compiler
generates a new class,
which derives from two

delegate classes provided
by the .NET Framework.
Module 8: Delegates and Events 15


Creating and Invoking Multicast Delegates
// assign to c the composition of delegates a and b
c = (MyDelegate2)Delegate.Combine(a, b);
// assign to d the result of removing a from c
d = (MyDelegate2)Delegate.Remove(c, a);
// Iterate through c's invocation list
// and invoke all delegates except a
Delegate[] DelegateList = c.GetInvocationList();
for (int i = 0; i < DelegateList.Length; i++) {
if (DelegateList[i].Target != aFoo1) {
((MyDelegate2) DelegateList[i])();
}
}
// assign to c the composition of delegates a and b
c = (MyDelegate2)Delegate.Combine(a, b);
// assign to d the result of removing a from c
d = (MyDelegate2)Delegate.Remove(c, a);
// Iterate through c's invocation list
// and invoke all delegates except a
Delegate[] DelegateList = c.GetInvocationList();
for (int i = 0; i < DelegateList.Length; i++) {
if (DelegateList[i].Target != aFoo1) {
((MyDelegate2) DelegateList[i])();
}
}


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The following sample code shows:
!
How to create multicast delegate objects.
!
How to write code to invoke delegates’ Combine and Remove methods.
!
How to write code to iterate through an invocation list invoking all
delegates, except those delegates whose target is a specific object.

Topic Objective
To provide specific
examples of how to create
and invoke multicast
delegates, and how to
iterate though an invocation
list to invoke specific
delegates.
Lead-in
This sample code shows
how to create and invoke
multicast delegates, and
how to iterate through an
invocation list to invoke
specific delegates.

16 Module 8: Delegates and Events


using System;

public delegate void MyDelegate2();

public class Foo
{
public void Bar() {
Console.WriteLine(
"
Bar invoked
"
);
}
}

class Application {
public static void Main() {
Foo aFoo1 = new Foo();
Foo aFoo2 = new Foo();

MyDelegate2 a, b, c, d;

a = new MyDelegate2(aFoo1.Bar);
b = new MyDelegate2(aFoo2.Bar);

// assign to delegate c the composition of delegates a and b
c = (MyDelegate2)Delegate.Combine(a , b);


// assign to d the result of removing a from c
d = (MyDelegate2)Delegate.Remove(c , a);

// iterate through c's invocation list
// and invoke all delegates except those that target aFoo1
Delegate[] DelegateList = c.GetInvocationList();
for (int i = 0; i < DelegateList.Length; i++) {
if (DelegateList[i].Target != aFoo1) {
((MyDelegate2) DelegateList[i])();
}
}
}
}

The preceding code invokes the delegate that invokes object aFoo2’s Bar
method and outputs:
Bar invoked

Module 8: Delegates and Events 17


C# Language-Specific Syntax
!
C# Delegates That Return Void Are Multicast Delegates
!
In C#, Use the + and - Operators to Add and Remove
Invocation List Entries
#
Less verbose than Combine and Remove methods

MyDelegate a, b, c, d;
a = new MyDelegate(Foo);
b = new MyDelegate(Bar);
c = a + b; // Compose two delegates to make another
d = c - a; // Remove a from the composed delegate
a += b; // Add delegate b to a's invocation list
a -= b; // Remove delegate b from a's list
MyDelegate a, b, c, d;
a = new MyDelegate(Foo);
b = new MyDelegate(Bar);
c = a + b; // Compose two delegates to make another
d = c - a; // Remove a from the composed delegate
a += b; // Add delegate b to a's invocation list
a -= b; // Remove delegate b from a's list

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Delegate types with a void return value in C# cause the compiler to derive the
delegate class from the MulticastDelegate class. You can also use these
delegates’ addition operator (+) and the subtraction operator (-) to invoke the
Combine and Remove methods for delegate composition and decomposition.
Topic Objective
To present helpful
alternative C# syntax.
Lead-in
Delegate types with a void
return value in C# cause the

compiler to derive the
delegate class from the
MulticastDelegate class.
18 Module 8: Delegates and Events


Demonstration: Multicast Delegates

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this demonstration, you will learn how to add and remove methods from the
invocation list of multicast delegates by using the + and – operators.
using System;

namespace Multicast_Delegates
{

delegate void MyDelegate3(string s);

class MyClass
{
public static void Hello(string s) {
Console.WriteLine(" Hello, {0}!", s);
}

public static void Goodbye(string s) {
Console.WriteLine(" Goodbye, {0}!", s);

}

(Code continued on the following page.)
Topic Objective
To demonstrate how to use
the + and – operators to add
and remove methods.
Lead-in
You can add and remove
methods from the invocation
list of multicast delegates by
using the + and – operators.
Delivery Tip
Use Visual Studio .NET to
run this code. Set
breakpoints or single-step to
illustrate the sequence of
events.
Module 8: Delegates and Events 19


public static void Main() {
MyDelegate3 a, b, c, d;
a = new MyDelegate3(MyClass.Hello);
b = new MyDelegate3(MyClass.Goodbye);
c = a + b; // Compose two delegates to make another
d = c - a; // Remove a from c to make another

Console.WriteLine("Invoking delegate a:");
a("A");

Console.WriteLine("Invoking delegate b:");
b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
Console.WriteLine("Invoking delegate d:");
d("D");

Console.WriteLine("Adding b to a and invoking:");
a += b; // Add the b delegate to a
a("E");
Console.WriteLine("Removing b from a and invoking:");
a -= b; // Remove the b delegate from a
a("F");
}
}

}

This code generates the following output:
Invoking delegate a:
Hello, A!
Invoking delegate b:
Goodbye, B!
Invoking delegate c:
Hello, C!
Goodbye, C!
Invoking delegate d:
Goodbye, D!
Adding b to a and invoking:
Hello, E!

Goodbye, E!
Removing b from a and invoking:
Hello, F!

20 Module 8: Delegates and Events


Delegate Details
!
A Delegate Declaration Causes the Compiler to
Generate a New Class
// delegate void MyDelegate3(string val);
class MyDelegate3 : System.MulticastDelegate {
public MyDelegate3(object obj, methodref mref)
: base (obj, mref) { //
}
public void virtual Invoke(string val) { //
}
};
// delegate void MyDelegate3(string val);
class MyDelegate3 : System.MulticastDelegate {
public MyDelegate3(object obj, methodref mref)
: base (obj, mref) { //
}
public void virtual Invoke(string val) { //
}
};

*****************************
ILLEGAL FOR NON

-
TRAINER USE
******************************
As previously noted in this module, when delegate declarations are compiled,
the compiler, in effect, generates a new class that derives from
System.Delegate. The new delegate class has two members: a constructor and
an Invoke method. The following class declaration resembles what the
compiler actually does:
// delegate void MyDelegate3(string val);

class MyDelegate3 : System.MulticastDelegate {
public MyDelegate3(object obj, methodref mref)
: base (obj, mref) {//
}
public void virtual Invoke(string val) {//
}
}

The first member is a constructor: its first parameter is the delegate’s target
object, and its second parameter is a reference to a method. When a delegate
refers to a static method, the target object is null.
The Invoke method for the class MyDelegate3 indicates that delegate instances
of this class encapsulate methods that have a void return and a single string
parameter. When a delegate is invoked, the Invoke method is called with the
specified parameters.
Topic Objective
To show how a delegate
declaration is handled by
the compiler.
Lead-in

When delegate declarations
are compiled, the compiler
generates a new class that
derives from
System.Delegate.
For Your Information
There is no actual type
named methodref, but
having an instance of a type
that encapsulates a
reference to a class method
resembles what the
compiler actually does.
Module 8: Delegates and Events 21


"
""
"

Events
!
Event Scenario
!
Declaring an Event
!
Connecting to an Event
!
Raising an Event
!

.NET Framework Guidelines

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
An event is a way for a class to notify clients of that class when some
interesting thing happens to an object. The most familiar use for events is in
graphical user interfaces. Typically the classes that represent controls in the
graphical user interface have events that are notified when a user manipulates
the control, as when a user clicks a button. However, the use of events is not
limited to graphical user interfaces. Events also allow an object to signal state
changes that may be useful to clients of that object. Events are an important
building block for creating classes that can be reused in many different
programs.
Delegates are particularly suited for implementing events. You can use the
.NET event mechanism to easily provide an object with type safe methods that
clients can call to register and deregister delegates to event handler methods.
When an event is raised, the event handler methods are called.
Topic Objective
To provide an overview of
the topics in this section.
Lead-in
An event is a way for a class
to notify clients of that class
of a change in an object.

×