1. Trang chủ
  2. » Công Nghệ Thông Tin

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

48 264 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 48
Dung lượng 0,95 MB

Nội dung

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); [...]... use these delegates addition operator (+) and the subtraction operator (-) to invoke the Combine and Remove methods for delegate composition and decomposition 18 Module 8: Delegates and Events Demonstration: Multicast Delegates 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. .. if (SwitchFlipped != null) { // call the delegate if non-null SwitchFlipped(this, e); } } // } Module 8: Delegates and Events 31 When to Use Delegates, Events, and Interfaces Topic Objective To explain when to use delegates, events, and interfaces ! Use a Delegate If: # Lead-in Delegates, interfaces, and events all provide callback functionality, but each has specific usage characteristics that make... 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 Module 8: Delegates and Events 15 Creating and Invoking Multicast Delegates 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. .. multicast delegates to allow the switch to control additional lights 14 Module 8: Delegates and Events Single vs Multicast Delegates Topic Objective To explain the difference between single-cast and 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 ! Multicast Delegates: ... first check for null and then call the event You can only raise an event from within the class that declared the event if (MouseClicked != null) MouseClicked(); 28 Module 8: Delegates and Events NET Framework Guidelines Topic Objective To introduce NET Framework guidelines for delegates and events ! ! Event Argument Classes Extend System.EventArgs ! Event Delegates Return Void and Have Two Arguments... 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 22 Module 8: Delegates and Events Event Scenario Topic Objective To... aFoo2’s Bar method and outputs: Bar invoked Module 8: Delegates and Events 17 C# Language-Specific Syntax 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 ! C# Delegates That Return Void Are Multicast Delegates ! In C#, Use the + and - Operators to Add and Remove Invocation... implementation of events easier, it also prevents clients from accessing or raising the delegates of other clients 25 26 Module 8: Delegates and Events Connecting to an Event Topic Objective To describe how to connect to and disconnect from an event ! ! Lead-in From outside the class that declared it, an event looks like a field, but access to that field is restricted Connect by Combining Delegates Disconnect... 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.) 9 10 Module 8: Delegates and Events public void OnFlip() { if (switchState == SwitchPosition.Down) { switchState... Use an appropriate and specific event class for its type Module 8: Delegates and Events ! 29 When necessary, event classes extend System.EventArgs and end in EventArgs, as in the following example: public class SwitchFlippedEventArgs : EventArgs {// } For events that do not use any additional information, the NET Framework has already defined an appropriate delegate type: EventHandler, whose argument . 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,. create and invoke multicast delegates, and how to iterate through an invocation list to invoke specific delegates. 16 Module 8: Delegates and Events

Ngày đăng: 17/01/2014, 08:20

TỪ KHÓA LIÊN QUAN

w