Module 12: Operators, Delegates, and Events 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 Module 12: Operators, Delegates, and Events
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.
Module 12: Operators, Delegates, and Events 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#.
Module 12: Operators, Delegates, and Events 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 Module 12: Operators, Delegates, and Events
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.
Module 12: Operators, Delegates, and Events 3
Operators and Methods
Using methods
Reduces clarity
Increases risk of errors, both syntactic and semantic
Using operators
Makes expressions clear
myIntVar1 = Int.Add(myIntVar2,
Int.Add(Int.Add(myIntVar3,
myIntVar4), 33));
myIntVar1 = Int.Add(myIntVar2,
Int.Add(Int.Add(myIntVar3,
myIntVar4), 33));
myIntVar1 = myIntVar2 + myIntVar3 + myIntVar4 + 33;
myIntVar1 = myIntVar2 + myIntVar3 + myIntVar4 + 33;
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The purpose of operators is to make expressions clear and easy to understand. It
would be possible to have a language with no operators, relying instead on
well-defined methods, but this would most likely have an adverse affect on the
clarity of the language.
Using Methods
For example, suppose the arithmetic addition operator was not present, and the
language instead provided an Add method of the Int class that took parameters
and returned a result. Then, to add two variables, you would write code similar
to the following:
myIntVar1 = Int.Add(myIntVar2, myIntVar3);
myIntvar2 = Int.Add(myIntVar2, 1);
Using Operators
By using the arithmetic addition operator, you can write the more concise lines
of code that follow:
myIntVar1 = myIntVar2 + myIntVar3;
myIntVar2 = myIntVar2 + 1;
Code would become almost indecipherable if you were to add a series of values
together by using the Add method, as in the following code:
myIntVar1 = Int.Add(myIntVar2, Int.Add(Int.Add(myIntVar3,
myIntVar4), 33));
If you use 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.
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.
4 Module 12: Operators, Delegates, and Events
Predefined C# Operators
Operator Categories
Operator Categories
Type informationAssignment
Indirection and addressOverflow exception control
Object creationRelational
Delegate concatenation and
removal
Shift
ConditionalIncrement and decrement
CastString concatenation
IndexingLogical (Boolean
and bitwise)
Member accessArithmetic
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The C# language provides a large set of predefined operators. Following is the
complete list.
Operator category Operators
Arithmetic +, -, *, /, %
Logical (Boolean and bitwise) &, |, ^, !, ~, &&, ||, true, false
String concatenation +
Increment and decrement ++,
Shift <<, >>
Relational ==, !=, <, >, <=, >=
Assignment =, +=, -=, *=, /=, %=, &=, |=, <<=, >>=
Member access .
Indexing [ ]
Cast ( )
Conditional ? :
Delegate concatenation and removal +, -
Object creation new
Type information is, sizeof, typeof
Overflow exception control checked, unchecked
Indirection and address *, ->, [ ], &
Topic Objective
To present the operators
defined by the C# language.
Lead-in
The C# language defines a
number of categories of
operators.
Module 12: Operators, Delegates, and Events 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 defined as
keywords rather than symbols, but their functionality with the data types and
classes supplied with the .NET Framework is completely defined.
Operators with Multiple Definitions
A confusing aspect of operators is that the same symbol may have several
different meanings. The + in the expression
10 + 5 is clearly the arithmetic
addition operator. You can determine the meaning by the context in which it is
used—no other meaning of + makes sense.
However, the following example uses the + operator to concatenate strings:
"Adam " + "Barr"
It is the function of the parser, when the program is compiled, to determine the
meaning of an operator in any given context.
6 Module 12: Operators, Delegates, and Events
Operator Overloading
Introduction to Operator Overloading
Overloading Relational Operators
Overloading Logical Operators
Overloading Conversion Operators
Overloading Operators Multiple Times
Quiz: Spot the Bugs
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Many predefined operators in C# perform well-defined functions on classes and
other data types. This clear definition widens the scope of expression for the
user. You can redefine some of the operators provided by C# and use them as
operators that work only with classes and structs that you have defined. In a
sense, this is the same as defining your own operators. This process is known as
operator overloading.
Not all predefined C# operators can be overloaded. The unary arithmetic and
logic operators can be overloaded freely, as can the binary arithmetic operators.
The assignment operators cannot be overloaded directly, but they are all
evaluated using the arithmetic, logical, and shift operators, which in turn can be
overloaded.
After completing this lesson, you will be able to:
Overload relational, logical, and conversion operators.
Overload an operator multiple times.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
You can change the way in
which C# interprets some
operators when they are
used on your classes.
Không có nhận xét nào:
Đăng nhận xét