Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
825,9 KB
Nội dung
Contents
Overview 1
Using Properties 2
Using Indexers 17
Lab 13.1: Using PropertiesandIndexers 33
Review 42
Module 13:Properties
and Indexers
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, 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.
Module13:PropertiesandIndexers iii
Instructor Notes
The obvious common feature of propertiesandindexers is that they both use
get and set accessor syntax. This module does not cover the more advanced
aspects of propertiesand indexers, such as their use in interfaces or their use
with virtual, abstract, override, and new modifiers.
After completing this module, students will be able to:
Create properties to encapsulate data within a class.
Define indexers to use objects with array-like notation.
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_13.ppt
Module 13, “Properties and Indexers”
Lab 13.1, Using PropertiesandIndexers
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
Presentation:
30 Minutes
Lab:
30 Minutes
iv Module13:PropertiesandIndexers
Module Strategy
Use the following strategy to present this module:
Using Properties
The first slide in this section is titled Why Use Properties? This slide
discusses conciseness and flexibility. The easiest way to present a
discussion about these topics is to demonstrate a simple int property and a
simple private int field with public get or set methods. Then compare using
an expression like
Value++ to using SetValue(o.GetValue( ) + 1).
Conduct a vote, asking which students prefer the latter.
The next topic is about using accessors. Concentrate on the syntax, which
might initially be unfamiliar to students. A property has a method-like body
but is declared without parentheses and parameters. It also has a strict
syntax. The body of a property can only contain a get accessor, a set
accessor, or both. You might want to demonstrate the code (type it in using
Microsoft Visual Studio
®) and show it failing to compile if the body
contains a simple declaration and no get or set. Mention that private
members of a class start with a lowercase letter by convention, and that
public members, including properties, start with a capital letter. The point of
this topic is that properties look like fields, so they should act like fields.
Logically, they are fields. A get accessor should have no side effects; a set
accessor should only have the obvious set side effect.
The next topic compares properties to fields. At this point, continue the
demonstration by showing a property being used. Place WriteLine
statements inside the get and set accessors to prove that they are executed in
read/write statements. Properties look and behave like fields. The word
computed in the first sub-bullet of the slide is important. It relates to the
logical aspect of properties. This point is further emphasized when you
consider the differences between propertiesand fields. Fields have
addresses and are physical, whereas properties do not have addresses and
are logical.
The next topic compares properties to methods. This topic emphasizes that
properties are not physical pieces of data, but rather are pieces of code. The
slide shows that properties can be virtual, abstract, or override. These
modifiers are not covered any further, nor are they used in the lab. Again,
you might want to prove this by demonstrating that a virtual property will
compile. This demonstration shows that properties are really methods and
not data.
In the slides and text of the Property Types topic, the word read is
deliberately separated from the word only. You need to try to make it clear
to students that read-only is not being used in the same way as the readonly
keyword. You can discuss write-only properties for completeness, but the
simple message is that write-only properties are rare, and students should
avoid using them. The slide reveals that properties can be static. You might
want to briefly mention this because the example slide shows a static
property defining an implementation of a “lazily created” Singleton.
Module13:PropertiesandIndexers v
Using Indexers
You should find the Using Indexers section straightforward. There are many
obvious similarities between indexersand properties. The important point is
that properties provide field-like access andindexers provide array-like
access. Indexers are a natural extension of properties. Properties are
logically single-element entities, whereas arrays are logically multiple-
element entities. The first slide describes the syntax for indexers. Provide an
example.
After you discuss the indexer syntax, you can compare arrays to indexers.
Indexers are more flexible because physically they are closely related to
methods. This comparison is made clear in the Comparing Indexers to
Arrays topic. Logically, they still do not denote storage locations and so are
also closely related to properties. This comparison is discussed in the
Comparing Indexers to Properties slide. Indexers can be static, which is
mentioned but not covered any further and is not required to complete the
lab.
The Using Indexers section concludes with two examples. The first example
shows the String class from the Microsoft .NET Framework software
development kit (SDK). The slide introduces the concept of immutable
classes. This is an important concept (more so in C# than it is in C++
because of the nature of C#), and you should ensure that students understand
what immutable means.
The second example shows the BitArray class. There is also a class called
BitArray in the .NET Framework SDK. This illustrates the logical nature of
indexers. There are two little-known bit operator expressions (
index >> 5
and
1 << index) that you might want to explain. (They are covered in the
student notes.)
Module13:PropertiesandIndexers 1
Overview
Using Properties
Using Indexers
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can expose the named attributes for a class by using either fields or
properties. Fields are implemented as member variables with private access. In
C#, properties appear to be fields to the user of a class, but they use methods to
get and set values.
C# provides an indexer feature that allows objects to be indexed in the same
way as an array.
In this module, you will learn how to use propertiesand indexers. You will
learn how to use properties to enable field-like access andindexers to enable
array-like access.
After completing this module, you will be able to:
Create properties to encapsulate data within a class.
Define indexers to gain access to classes by using array-like notation.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about properties, which
provide field-like access,
and about indexers, which
provide array-like access.
2 Module13:PropertiesandIndexers
Using Properties
Why Use Properties?
Using Accessors
Comparing Properties to Fields
Comparing Properties to Methods
Property Types
Property Example
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
After completing this lesson, you will be able to:
Use properties to encapsulate data in a class.
Use properties to access data in a class.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
Logically, properties are like
fields, so this section
discusses the issues of
read/write access.
Physically, properties are
like methods, so this section
also compares properties to
methods.
Module13:PropertiesandIndexers 3
Why Use Properties?
Properties provide:
A useful way to encapsulate information inside a class
Concise syntax
Flexibility
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Properties provide a useful way to encapsulate data within a class. Examples of
properties include the length of a string, the size of a font, the caption of a
window, the name of a customer, and so on.
Concise Syntax
C# adds properties as first-class elements of the language. Many existing
languages, such as Microsoft
® Visual Basic®, already have properties as first-
class elements of the language. If you think of a property as a field, it can help
you to focus on the application logic. Compare, for example, the following two
statements. The first statement does not use properties, whereas and the second
does use properties.
o.SetValue(o.GetValue( ) + 1);
o.Value++;
The statement that uses a property is certainly easier to understand and much
less error prone.
Topic Objective
To explain some of the
benefits of using properties.
Lead-in
Properties provide a useful
way to encapsulate
information inside a class.
4 Module13:PropertiesandIndexers
Flexibility
To read or write the value of a property, you use field-like syntax. (In particular,
you do not use parentheses.) However, the compiler translates this field-like
syntax into encapsulated method-like get and set accessors. For example, Value
could be a property of the object o in the expression o.Value, which will cause
the statements inside the get accessor “method” for the Value property to be
executed. This separation allows the statements inside the get and set accessors
of a property to be modified without affecting the use of the property, which
retains its field-like syntax. Because of this flexibility, you should use
properties instead of fields whenever possible.
When you expose state through a property, your code is potentially less
efficient than when you expose state directly through a field. However, when a
property contains only a small amount of code and is non-virtual (which is
frequently the case), the execution environment can replace calls to an accessor
with the actual code of the accessor. This process is known as inlining, and it
makes property access as efficient as field access, yet it preserves the increased
flexibility of properties.
[...]... void ByOut(out string name) { } } Module13:PropertiesandIndexers 23 Comparing Indexers to Properties Topic Objective To compare indexers to properties Lead-in Indexers are based upon propertiesand share many of the features of properties Similarities Both use get and set accessors Neither have an address Neither can be void Differences Indexers can be overloaded Indexers cannot be static *****************************ILLEGAL... 20 Module13:PropertiesandIndexers Comparing Indexers to Arrays Topic Objective To compare indexers to arrays Similarities Lead-in Although indexers use array notation, there are some differences between indexersand arrays Both use array notation Differences Indexers can use non-integer subscripts Indexers can be overloaded—you can define several indexers, each using a different index type Indexers. .. FOR NON-TRAINER USE****************************** Indexers are based on properties, andindexers share many of the features of propertiesIndexers also differ from properties in certain ways To understand indexers fully, it is helpful to compare them to properties Similarities with PropertiesIndexers are similar to properties in many ways: Both use get and set accessors Neither denote physical storage... (StreamReader is derived from TextReader.) Module13:PropertiesandIndexers 17 Using Indexers Topic Objective To provide an overview of the topics covered in this section What Is an Indexer? Lead-in Comparing Indexers to Arrays Indexers are members that are accessed like arrays but implemented like properties Comparing Indexers to Properties Using Parameters to Define Indexers String Example BitArray Example... oed["life"] is an expression of type string and could not be an expression of type void 24 Module13:PropertiesandIndexers Differences from Properties It is also important to understand how indexersandproperties differ: Identification A property is identified only by its name An indexer is identified by its signature; that is, by the square brackets and the type of the indexing parameters Overloading... Method(double d1, decimal d2) { } } Properties cannot be of type void, although methods can class Example { public void Property { } // Compile-time error public void Method( ) { } // Okay } 13 14 Module13:PropertiesandIndexers Property Types Topic Objective To show how to create readonly and write-only properties Read/write properties Lead-in Read-only properties If a property does not have... both the speed and the color of the thing object thing.speed = 5; However, sometimes set accessor side effects can be useful For example, a shopping basket object could update its total whenever the item count in the basket is changed Module 13:PropertiesandIndexers 7 Comparing Properties to Fields Topic Objective To compare properties to fields Properties are “logical fields” Lead-in Properties are... Methods Propertiesand methods differ in a few important ways, as summarized in the following table Feature Properties Methods Use parentheses No Yes Specify arbitrary parameters No Yes Use void type No Yes Module13:PropertiesandIndexers Consider the following examples: Properties do not use parentheses, although methods do class Example { public int Property { } public int Method( ) { } } Properties. .. enables an object to be indexed in the same way as an array Whereas you can use properties to enable field-like access to the data in your class, you can use indexers to enable array-like access to the members of your class After completing this lesson, you will be able to: Define indexers Use indexers 18 Module13:PropertiesandIndexers What Is an Indexer? Topic Objective To define the purpose of an indexer... void ByRef(ref string name) { } static void ByOut(out string name) { } } 9 10 Module13:PropertiesandIndexers Comparing Properties to Methods Topic Objective To compare properties to methods Lead-in In the previous topic, you saw that using properties is similar to using fields In this topic, you will see that using properties is similar to using methods Similarities Both contain code to be executed .
Overview 1
Using Properties 2
Using Indexers 17
Lab 13.1: Using Properties and Indexers 33
Review 42
Module 13: Properties
and Indexers
Information. Module 13: Properties and Indexers
Using Properties
Why Use Properties?
Using Accessors
Comparing Properties to Fields
Comparing Properties