Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 8: Delegates and Events

1

 

 

 

Overview

Topic Objective

To provide an overview of the module topics and objectives.

Lead-in

Delegates are the objectoriented equivalents of function pointers.

!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 eventhandling 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.

2Module 8: Delegates and Events

" Delegates

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.

!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.

Module 8: Delegates and Events

3

 

 

 

Delegate Scenario

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.

1 - Change in

Switch Object

switch position

invokes switch’s

 

OnFlip method

 

Light Object

OnFlip method

2 - OnFlip Method

invokes delegate

Delegate object

OnFlipCallback

Delegate object

method

3 - Delegate invokes light’s

4 - OnFlipCallback method

OnFlipCallback method

changes light’s state

*****************************ILLEGAL FOR NON-TRAINER USE******************************

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.

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.

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.

4Module 8: Delegates and Events

Declaring a Delegate

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.

! 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 // declares a delegate for a method that takes a single // argument of type string and has a void return type // argument of type string and has a void return type delegate void MyDelegate1(string s);

delegate void MyDelegate1(string s);

*****************************ILLEGAL FOR NON-TRAINER USE******************************

For Your Information

The details of how the common language runtime creates delegates are presented later in this module.

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);

Module 8: Delegates and Events

5

 

 

 

Instantiating a Delegate

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.

! A Delegate Object Is Created with the new Operator ! Delegate Objects Are Immutable

// instantiating a delegate to a static method Hello // instantiating a delegate to a static method Hello // in the class MyClass

// in the class MyClass

MyDelegate1 a = new MyDelegate1(MyClass.Hello); MyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to an instance method // instantiating a delegate to an instance method // AMethod in object p

// AMethod in object p MyClass p = new MyClass(); MyClass p = new MyClass();

MyDelegate1 b = new MyDelegate1(p.AMethod); MyDelegate1 b = new MyDelegate1(p.AMethod);

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delivery Tip

To place the delegate instantiation code in a fuller context, refer to the following code example.

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.

6Module 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

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.

!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

//given the previous delegate declaration and

//instantiation, the following invokes MyClass'

//instantiation, the following invokes MyClass'

//static method Hello with the parameter "World"

//static method Hello with the parameter "World"

a("World");

a("World");

*****************************ILLEGAL FOR NON-TRAINER USE******************************

For Your Information

Refer to the previous slide on delegate declaration and instantiations.

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");

8Module 8: Delegates and Events

Demonstration: Using Delegates

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.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delivery Tip

Use Visual Studio .NET to run the following code. Set breakpoints or single step to illustrate the sequence of events.

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.

Module 8: Delegates and Events

9

 

 

 

For Your Information

As noted in C# LanguageSpecific 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.

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.)

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);

}

}

}

Соседние файлы в папке c#