Thứ Bảy, 8 tháng 2, 2014

Tài liệu Module 13: Properties and Indexers pptx

Module 13: Properties and Indexers v


 Using Indexers
You should find the Using Indexers section straightforward. There are many
obvious similarities between indexers and properties. The important point is
that properties provide field-like access and indexers 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.)


Module 13: Properties and Indexers 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 properties and indexers. You will
learn how to use properties to enable field-like access and indexers 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 Module 13: Properties and Indexers




 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.
Module 13: Properties and Indexers 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 Module 13: Properties and Indexers


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.
Module 13: Properties and Indexers 5


Using Accessors
 Properties provide field-like access
 Use get accessor statements to provide read access
 Use set accessor statements to provide write access
class Button
{
public string Caption // Property
{
get { return caption; }
set { caption = value; }
}
private string caption; // Field
}
class Button
{
public string Caption // Property
{
get { return caption; }
set { caption = value; }
}
private string caption; // Field
}

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
A property is a class member that provides access to a field of an object. You
use a property to associate actions with the reading and writing of an object’s
attribute. A property declaration consists of a type and a name and has either
one or two pieces of code referred to as accessors. These accessors are as
follows:
 get accessor
 set accessor

Accessors have no parameters. A property does not need to have both a get
accessor and a set accessor. For example, a read-only property will provide
only a get accessor. You will learn more about read-only properties later in this
section.
Using the get Accessor
The get accessor of a property returns the value of the property. The following
code provides an example:
public string Caption
{
get { return caption; }

}

Topic Objective
To describe how to use the
get and set accessors.
Lead-in
How do you get or set
access to fields of an
object?
6 Module 13: Properties and Indexers


You implicitly call a property’s get accessor when you use that property in a
read context. The following code provides an example:
Button myButton;

string cap = myButton.Caption; // Calls "myButton.Caption.get"

Notice that you do not use parentheses after the property name. In this example,
the statement
return caption; returns a string. This string is returned
whenever the value of the Caption property is read.
Reading a property should not change the object’s data. When you invoke a get
accessor, it is conceptually equivalent to reading the value of a field. A get
accessor should not have observable side effects.
Using the set Accessor
The set accessor of a property modifies the value of a property.
public string Caption
{

set { caption = value; }
}

You implicitly call a property’s set accessor when you use that property in a
write context—that is, when you use it in an assignment. The following code
provides an example:
Button myButton;

myButton.Caption = "OK"; // Calls "myButton.Caption.set"

Notice again that you do not use parentheses. The variable value contains the
value that you are assigning and is created automatically by the compiler. Inside
the set accessor for the Caption property, value can be thought of as a string
variable that contains the string “OK.” A set accessor cannot return a value.
Invoking a set accessor is syntactically identical to a simple assignment, so you
should limit its observable side effects. For example, it would be somewhat
unexpected for the following statement to change 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: Properties and Indexers 7


Comparing Properties to Fields
 Properties are “logical fields”
 The get accessor can return a computed value
 Similarities
 Syntax for creation and use is the same
 Differences
 Properties are not values; they have no address
 Properties cannot be used as ref or out parameters to
methods

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
As an experienced developer, you already know how to use fields. Because of
the similarities between fields and properties, it is useful to compare these two
programming elements.
Properties Are Logical Fields
You can use the get accessor of a property to calculate a value rather than return
the value of a field directly. Think of properties as logical fields—that is, fields
that do not necessarily have a direct physical implementation. For example, a
Person class might contain a field for the person’s date of birth and a property
for the person’s age that calculates the person’s age:
class Person
{
public Person(DateTime born)
{
this.born = born;
}

public int Age
{
// Simplified
get { return DateTime.UtcNow.Year – born.Year; }
}

private readonly DateTime born;
}

Topic Objective
To compare properties to
fields.
Lead-in
Properties are similar to
fields in many ways.
8 Module 13: Properties and Indexers


Similarities with Fields
Properties are a natural extension of fields. Like fields, they:
 Specify a name with an associated non-void type, as shown:
class Example
{
int field;
int Property { }
}

 Can be declared with any access modifier, as shown:
class Example
{
private int field;
public int Property { }
}

 Can be static, as shown:
class Example
{
static private int field;
static public int Property { }
}

 Can hide base class members of the same name, as shown:
class Base
{
public int field;
public int Property { }
}
class Example: Base
{
public int field;
new public int Property { }
}

 Are assigned to or read from by means of field syntax, as shown:
Example o = new Example( );
o.field = 42;
o.Property = 42;

Không có nhận xét nào:

Đăng nhận xét