Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 74 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
74
Dung lượng
0,98 MB
Nội dung
Contents
Overview 1
Introduction to Operators 2
Operator Overloading 6
Lab 12.1: Defining Operators 19
Creating and Using Delegates 37
Defining and Using Events 47
Demonstration: Handling Events 53
Lab 12.2: Defining and Using Events 54
Review 63
Course Evaluation 65
Module 12:Operators,
Delegates, andEvents
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, andevents depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events 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, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, IntelliSense, JScript, MSDN,
PowerPoint, SQL Server, Visual Basic, Visual C++, Visual C#, Visual J#, Visual Studio, and
Win32 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.
Module12:Operators,Delegates,andEvents iii
Instructor Notes
This module covers three areas of useful functionality that may be implemented
in a class; namely, operators,delegates,and events.
After completing this module, students will be able to:
Use operators to manipulate the types and classes supplied with the
Microsoft
® .NET Framework.
Use delegates to decouple a method call from its implementation.
Add event specifications to a class to allow subscribing classes to be
notified of changes in object state.
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 following materials:
Microsoft PowerPoint® file 2124C_12.ppt
Module 12, “Operators, Delegates,and Events”
Lab 12.1, Defining Operators
Lab 12.2, Defining and Using Events
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the labs.
Read the instructor notes and margin notes for the module.
Practice the Handling Events demonstration. The StockMarket project is in
the install folder\DemoCode\Mod12\StockMarket folder.
Presentation:
60 Minutes
Labs:
60 Minutes
iv Module12:Operators,Delegates,andEvents
Demonstration
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Handling Events
To explain the scenario
1. A model of part of a stock market and two stock brokers has been written as
a Microsoft Visual C#
™
project called StockMarket.
2. When executed, the program creates two stock brokers (Honest John and
Shady Fred) and displays a form allowing the user to create stocks and edit
stock prices.
3. When prices rise and fall, RisingStock and CrashingStock events may be
generated.
4. Honest John subscribes to the RisingStock and CrashingStock events.
5. Shady Fred only subscribes to the RisingStock event.
To explain the code
1. Display the Stock class to show how events are published and raised.
Identify the following items:
a. The CrashingStock and RisingStock events.
b. The StockHandlerEvent delegate.
c. The AddOnCrashingStock and RemoveOnCrashingStock methods.
These are the public methods that objects can use to subscribe to, or
unsubscribe from, the crashingStock event.
d. The AddOnRisingStock and RemoveOnRisingStock methods. These
are the public methods that objects can use to subscribe to, or
unsubscribe from, the RisingStock event.
e. The OnCrashingStock and OnRisingStock methods, which raise the
events.
f. The setPrice method, which calls OnCrashingStock and
OnRisingStock.
2. Display the StockBroker class to show how events are handled when
raised. Identify the following items:
a. The StockCrashing method. This method handles the CrashingStock
event.
b. The StockRising method. This method handles the RisingStock event.
3. Display the StockMarketForm class to show how to subscribe to the
events. Identify the following items:
a. The Main method, which creates the two StockBroker objects (Honest
John and Shady Fred).
b. The cmdNew_Click method, which is executed when a new stock is
added to the market. This creates three StockEventHandler delegates.
Two delegates are for Honest John, and are tied to the RisingStock and
CrashingStock events. The third delegate is for Shady Fred, who
subscribes only to the RisingStock event.
Module12:Operators,Delegates,andEvents v
To demonstrate the application
1. Compile and execute the program.
2. The price form will be displayed. Add the following stock item:
• Ticker: ABCD
• Price: 200
• Threshold: 50
3. Click New. A dialog box will appear confirming the addition of the new
stock.
4. Add another stock item:
• Ticker: WXYZ
• Price: 100
• Threshold: 30
5. Click New. A dialog box will appear confirming the addition of the new
stock.
6. In the Ticker field, enter ABCD, and then click Find. The data for the
ABCD item will appear.
7. Change the price to 204, and then click Change. A dialog box will appear
confirming the price change.
8. Change the price again, to 220, and then click Change. The BUY BUY
BUY dialog boxes of Honest John and Shady Fred will appear when the
RisingStock event is raised. Acknowledge them both.
9. In the Ticker field, enter WXYZ, and then click Find. The data for the
WXYZ item will appear.
10. Change the price to 28, and then click Change. Only Honest John’s SELL
SELL SELL dialog box will appear. (The CrashingStock event was raised,
and only Honest John, not Shady Fred, subscribes to this event.)
vi Module12:Operators,Delegates,andEvents
Module Strategy
Use the following strategy to present this module:
Introduction to Operators
Begin with an explanation of the similarities and differences between
operators and methods. Explain to C++ developers that all operators are
public static methods. On the other hand, the related methods such as
ToString and Equals are instance methods. Then, after a brief discussion of
predefined C# operators, explain how data conversion operators can be used
for implicit and explicit conversion. Take a little time to explain the
difference between an explicit conversion that uses a cast and an implicit
conversion, and to explain the rationale for defining a conversion as either
explicit or implicit. Discuss issues such as whether an exception can be
raised and whether the conversion will always work without losing
information. Take a little time to describe the syntax of the conversion
operators, because this topic has some subtleties.
Operator Overloading
Begin by discussing how to define operators for manipulating classes and
structs and by introducing the concept of operator overloading. Explain that
many C# operators cannot be overridden. Having introduced the basics of
operator overloading in the first topic, explain how to overload relational
operators. Explain that relational operators are always overloaded in pairs.
Also, describe how the Equals method that the class inherits must be
overridden to ensure consistency when two objects of the class are
compared. Then discuss how to overload logical operators indirectly by
evaluating them in terms of operators that can be overloaded. The third set
of operators to be discussed from the overloading perspective is conversion
operators. Provide examples of data conversion operators that you can
define and point out that the class overrides the inherited ToString method.
In the last topic in this section, describe how to further overload operators to
provide alternative implementations that take different types as parameters.
The Time class used for many of the examples in these sections is available
in a Microsoft Visual Studio
® project in the install folder\DemoCode\Time
folder.
The lab for this section asks students to define operators for bank accounts
created in earlier labs, and for a new class of object: rational numbers. You
should explain what a rational number is if students do not know.
Creating and Using Delegates
Delegates are covered as a lead-in to events. To provide motivation for
defining and using delegates, the section uses a case study about a power
station attached to a nuclear reactor. Explain the scenario clearly, discussing
the problem and two possible solutions. Then discuss how the second
solution is more feasible than the first, and discuss its implementation
details. Explain the procedure for defining and creating delegates,and then
discuss how to use them to call methods.
Ensure that students understand how delegates work before discussing
events.
Module12:Operators,Delegates,andEvents vii
Defining and Using Events
Spend some time explaining event handling in C#. Explain the roles played
by publishers and subscribers. Then explain how an event is defined and
how objects can subscribe to it. Also, explain how a subscriber is notified
when an event occurs. Stress the multicast nature of events. It will be useful
to explain each step in the sequence of how an event is published,
subscribed to, and raised. Next, discuss how to pass parameters to methods
when using events. Explain that they should be wrapped in a single class.
An object can subscribe to more than one event from different publishers, so
describe how to pass information about the publisher that raised the event.
Then discuss the importance of providing the AddOnEvent and
RemoveOnEvent methods to subscribe to and unsubscribe from an event.
Also, discuss adding an OnEvent method to raise the event, and encasing
any parameters in an EventArgs object.
Demonstrate how events can be used to communicate information between
objects, and describe how event notification works in C#.
Module12:Operators,Delegates,andEvents 1
Overview
Introduction to Operators
Operator Overloading
Creating and Using Delegates
Defining and Using Events
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
This module covers three areas of useful functionality: operators,delegates,and
events.
Operators are the basic components of a language. You use operators to
perform manipulations and comparisons between variables that may be logical,
relational, or conditional in nature.
Delegates specify a contract between an object that issues calls to a function
and an object that implements the called function.
Events provide the way for a class to notify its clients when a change occurs in
the state of any of its objects.
After completing this module, you will be able to:
Define operators, to make a class or struct easier to use.
Use delegates to decouple a method call from a method implementation.
Add event specifications to a class to allow subscribing classes to be
notified of changes in object state.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how to define operators, use
delegates, and add events.
2 Module12:Operators,Delegates,andEvents
Introduction to Operators
Operators and Methods
Predefined C# Operators
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Operators are different from methods. They have special requirements that
enable them to function as expected. C# has a number of predefined operators
that you can use to manipulate the types and classes supplied with the
Microsoft
® .NET Framework.
After completing this lesson, you will be able to:
Identify why C#, like most languages, has operators.
Define operators, to make a class or struct easier to use.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
C# has a number of
predefined operators that
perform well-defined
functions on the supplied
.NET Framework classes
and types.
[...]... int hours; private int minutes; } Module12:Operators,Delegates,andEvents 9 Overloading Relational Operators Topic Objective To describe how to overload the relational operators Lead-in There are rules and guidelines for redefining relational operators Relational operators must be paired < and > = == and != Override the Equals method if overloading == and != Override the GetHashCode method... also override the GetHashCode method 10 Module12:Operators,Delegates,andEvents Example Delivery Tip Point out that == and != are based upon the Equals method, how the < operator works, and how the remaining relational operators use < and == to guarantee consistency The following code shows how to implement the relational operators, the Equals method, and the GetHashCode method for the Time struct:.. .Module 12:Operators,Delegates,andEvents 3 Operators and Methods Topic Objective To compare, and distinguish between, operators and methods Lead-in In addition to using method names that follow strict rules, operators also have other requirements Using methods Reduces clarity Increases risk of errors, both syntactic and semantic myIntVar1 = Int.Add(myIntVar2,... } } 11 12 Module12:Operators,Delegates,andEvents Overloading Logical Operators Topic Objective To describe how to overload the logical operators Lead-in Although you cannot overload the && and || operators directly, you can overload them indirectly if you understand how they are evaluated Operators && and || cannot be overloaded directly They are evaluated in terms of &, |, true, and false, which... multiplication, division, and casting Override the Equals, ToString, and GetHashCode methods Prerequisites Before working on this lab, you must be familiar with the following: Using inheritance in C# Defining constructors and destructors Compiling and using assemblies Basic C# operators Estimated time to complete this lab: 30 minutes 20 Module12:Operators,Delegates,andEvents Exercise 1 Defining... the BankAccount objects with the same balance and account type b Store the account numbers generated in two long variables called accNo1 and accNo2 22 Module12:Operators,Delegates,andEvents 4 Create two BankAccount variables called acc1 and acc2 Populate them with the two accounts created in the previous step by calling Bank.GetAccount() 5 Compare acc1 and acc2 by using the == operator This test... of operator != to compare the contents of the two BankAccount objects If the account number, type, and balance of both accounts are the same, return false; otherwise return true You can achieve this by calling operator == and inverting the result Module 12:Operators,Delegates,andEvents 21 7 Save and compile the project The project should now compile successfully The previous error was caused by... Indirection and address *, ->, [ ], & Module12:Operators,Delegates,andEvents 5 You use operators for building expressions The function of most operators is well understood For example, the addition operator (+) in the expression 10 + 5 will perform arithmetic addition, and in this example the expression will yield the value of 15 Some of the operators may not be as familiar as others, and some are... acc2, and acc3, as shown in the following code The WriteLine method uses ToString to format its arguments as strings Console.WriteLine("acc1 – {0}", acc1); Console.WriteLine("acc2 – {0}", acc2); Console.WriteLine("acc3 – {0}", acc3); 4 Call the Dispose method for each account object 5 Compile and run the test harness Check the results 26 Module12:Operators,Delegates,andEvents Exercise 2 Handling... methods in this way, the likelihood of errors, both syntactic and semantic, is enormous Operators are actually implemented as methods by C#, but their syntax is designed to make them easy to use The C# compiler and runtime automatically convert expressions with operators into the correct series of method calls 4 Module12:Operators,Delegates,andEvents Predefined C# Operators Topic Objective Operator .
the module topics and
objectives.
Lead-in
In this module, you will learn
how to define operators, use
delegates, and add events.
2 Module 12: Operators,. discussing
events.
Module 12: Operators, Delegates, and Events vii
Defining and Using Events
Spend some time explaining event handling in C#. Explain