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

Tài liệu Module 9: Creating and Destroying Objects ppt

Module 9: Creating and Destroying Objects v


 Initializing Data
Using Initializer Lists. It might not immediately be apparent why
constructors contain duplicate code, so explain the simple example that is in
the notes.
Initializing Readonly Fields. Remind students that readonly is a keyword,
and remind them what it means. Discuss the equivalence that is mentioned
in the notes.
Declaring a Constructor for a Struct. The constructor rules for structs and
classes are different. If you have mentioned this already, this topic will be
less of a surprise. The tip mentioned in the notes follows from these rules:
ensure that any struct type you declare is valid with all fields set to zero.
Using Private Constructors. Again, it is best to mention this earlier to
prepare the students. There are several reasons why non-public constructors
are useful. Do not get drawn into too much discussion here because later
modules explain this in more detail. Explain simple procedural methods
such as Sin and Cos.
Using Static Constructors. You could spend a lot of time on this topic, but
just explain the essential information. Remember that this course is only an
introduction to C#. C# is a dynamic language, like Java and unlike C++. It
has a class loader and can dynamically load classes across the Internet upon
demand. Often classes need to be initialized just like objects do.
 Objects and Memory
Object Lifetime. Discuss the entire life cycle of an object, including a brief
review of how objects are created. Between the creation and destruction of
an object, you can use the object only by calling a method. The final point
of the topic is that the destruction of an object is a two-step process, and that
these two steps are the reverse of the two steps used to create an object:
remove the initialization of the object back to raw memory, and then return
the raw memory to the heap.
Objects and Scope. The wording on the slide is deliberate. A local value is
determined by its declared scope. This is not true for an object. You do not
know when an object will be destroyed.
Garbage Collection. This topic relates to the previous topic. You do not
know when an object will be destroyed. In other words, the destruction of
objects is non-deterministic. Emphasize this point strongly. C++
programmers will be accustomed to destroying objects by using delete
statements, but in C# you can never deterministically destroy an object.
Garbage collection destroys the object for you. You might need to explain
what the word unreachable means.
vi Module 9: Creating and Destroying Objects


 Resource Management
Object Cleanup. Review the two steps that occur when an object is
destroyed. First, it is converted back to raw memory. Then, garbage
collection reclaims the raw memory. You cannot control the second step,
but you can specify instructions that will execute when an object is
converted back to raw memory. This is done in the destructor.
Writing Destructors. It is important to ensure that C++ programmers realize
that a C# destructor is not really like a C++ destructor at all. You cannot call
the C# destructor. This topic focuses on the syntax of the destructor. The
relationship between the destructor and Finalize is also covered.
IDisposable Interface and Dispose Method. Garbage collection frees the
memory that has been used by managed objects. Because a managed object
may encapsulate other non-memory resources, such as database connections
and so on, and because such resources are limited, you need to reclaim them
deterministically in code. This lesson covers how to perform explicit
resource management by using the IDisposable interface and the Dispose
method. The points on the slide provide four implementation tips. These tips
are elaborated upon in the notes, and code examples are provided.
The using Statement in C#. In a temporary resource use scenario, you
allocate, use, and dispose of a resource in a short period of time. C# allows
you to do this with a using statement. This technique enables you to avoid
using a try-finally block to release the resource.

Module 9: Creating and Destroying Objects 1


Overview
 Using Constructors
 Initializing Data
 Objects and Memory
 Resource Management

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
In this module, you will learn what happens when an object is created, how to
use constructors to initialize objects, and how to use destructors to destroy
objects. You will also learn what happens when an object is destroyed and how
garbage collection reclaims memory.
After completing this module, you will be able to:
 Use constructors to initialize objects.
 Create overloaded constructors that can accept varying parameters.
 Describe the lifetime of an object and what happens when it is destroyed.
 Create destructors.
 Implement the Dispose method.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how to control the process
of creating and destroying
objects.
2 Module 9: Creating and Destroying Objects




 Using Constructors
 Creating Objects
 Using the Default Constructor
 Overriding the Default Constructor
 Overloading Constructors

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Constructors are special methods that you use to initialize objects when you
create them. Even if you do not write a constructor yourself, a default
constructor is provided for you whenever you create an object from a reference
type.
After completing this lesson, you will be able to:
 Use default constructors.
 Use constructors to control what happens when an object is created.

Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this section, you will learn
about constructors and how
to use constructors to
initialize objects.
Module 9: Creating and Destroying Objects 3


Creating Objects
 Step 1: Allocating memory
 Use new keyword to allocate memory from the heap
 Step 2: Initializing the object by using a constructor
 Use the name of the class followed by parentheses
Date when = new Date( );
Date when = new Date( );

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The process of creating an object in C# involves two steps:
1. Use the new keyword to acquire and allocate memory for the object.
2. Write a constructor to turn the memory acquired by new into an object.

Even though there are two steps in this process, you must perform both steps in
one expression. For example, if Date is the name of a class, use the following
syntax to allocate memory and initialize the object when:
Date when = new Date( );

Step 1: Allocating Memory
The first step in creating an object is to allocate memory for the object. All
objects are created by using the new operator. There are no exceptions to this
rule. You can do this explicitly in your code, or the compiler will do it for you.
In the following table, you can see examples of code and what they represent.
Code example Represents

string s = "Hello"; string s = new string(new char[]{'H','e','l','l','o'});
int[ ] array = {1,2,3,4}; int[ ] array = new int[4]{1,2,3,4};

Topic Objective
To describe the process of
creating an object.
Lead-in
In C#, the only way you can
create an object is to use
the new keyword to allocate
memory.
4 Module 9: Creating and Destroying Objects


Step 2: Initializing the Object by Using a Constructor
The second step in creating an object is to call a constructor. A constructor
turns the memory allocated by new into an object. There are two types of
constructors: instance constructors and static constructors. Instance constructors
are constructors that initialize objects. Static constructors are constructors that
initialize classes.
How new and Instance Constructors Collaborate
It is important to realize how closely new and instance constructors collaborate
to create objects. The only purpose of new is to acquire raw uninitialized
memory. The only purpose of an instance constructor is to initialize the
memory and convert it into an object that is ready to use. Specifically, new is
not involved with initialization in any way, and instance constructors are not
involved in acquiring memory in any way.
Although new and instance constructors perform separate tasks, as a
programmer you cannot use them separately. This is one way for C# to help
guarantee that memory is always definitely set to a valid value before it is read.
(This is called definite assignment.)

In C++, you can allocate memory and not initialize
it (by directly calling operator new). You can also initialize memory allocated
previously (by using placement new). This separation is not possible in C#.

Note to C++ Pro
g
rammers
Module 9: Creating and Destroying Objects 5


Using the Default Constructor
 Features of a default constructor
 Public accessibility
 Same name as the class
 No return type—not even void
 Expects no arguments
 Initializes all fields to zero, false or null
 Constructor syntax
class Date { public Date( ) { } }
class Date { public Date( ) { } }

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
When you create an object, the C# compiler provides a default constructor if
you do not write one yourself. Consider the following example:
class Date
{
private int ccyy, mm, dd;
}

class Test
{
static void Main( )
{
Date when = new Date( );

}
}

The statement inside Test.Main creates a Date object called when by using
new (which allocates memory from the heap) and by calling a special method
that has the same name as the class (the instance constructor). However, the
Date class does not declare an instance constructor. (It does not declare any
methods at all.) By default, the compiler automatically generates a default
instance constructor.
Topic Objective
To describe what happens if
you do not write a
constructor yourself.
Lead-in
If you do not write a
constructor, the compiler
writes one for you!
6 Module 9: Creating and Destroying Objects


Features of a Default Constructor
Conceptually, the instance constructor that the compiler generates for the Date
class looks like the following example:
class Date
{
public Date( )
{
ccyy = 0;
mm = 0;
dd = 0;
}
private int ccyy, mm, dd;
}

The constructor has the following features:
 Same name as the class name
By definition, an instance constructor is a method that has the same name as
its class. This is a natural and intuitive definition and matches the syntax
that you have already seen. Following is an example:
Date when = new Date( );

 No return type
This is the second defining characteristic of a constructor. A constructor
never has a return type—not even void.
 No arguments required
It is possible to declare constructors that take arguments. However, the
default constructor generated by the compiler expects no arguments.
 All fields initialized to zero
This is important. The compiler-generated default constructor implicitly
initializes all non-static fields as follows:
• Numeric fields (such as int, double, and decimal) are initialized to zero.
• Fields of type bool are initialized to false.
• Reference types (covered in an earlier module) are initialized to null.
• Fields of type struct are initialized to contain zero values in all their
elements.
 Public accessibility
This allows new instances of the object to be created.


Module 10, “Inheritance in C#,” in Course 2124C, Programming with
C#, covers abstract classes. The compiler-generated default constructor for an
abstract class has protected access.

For Your Information
These default initializations
almost ensure that the
compiler-generated default
constructor never throws an
exception, but not quite.
There could be a base class
with its own default
constructor, which of course
is implicitly called by the
:base( ) syntax. (Use of
base is not covered in this
module.)
Note
Module 9: Creating and Destroying Objects 7


Overriding the Default Constructor
 The default constructor might be inappropriate
 If so, do not use it; write your own!
class Date
{
public Date( )
{
ccyy = 1970;
mm = 1;
dd = 1;
}
private int ccyy, mm, dd;
}
class Date
{
public Date( )
{
ccyy = 1970;
mm = 1;
dd = 1;
}
private int ccyy, mm, dd;
}

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Sometimes it is not appropriate for you to use the compiler-generated default
constructor. In these cases, you can write your own constructor that contains
only the code to initialize fields to non-zero values. Any fields that you do not
initialize in your constructor will retain their default initialization of zero.
What If the Default Constructor Is Inappropriate?
There are several cases in which the compiler-generated default constructor
may be inappropriate:
 Public access is sometimes inappropriate.
The Factory Method pattern uses a non-public constructor. (The Factory
Method pattern is discussed in Design Patterns: Elements of Reusable
Object-Oriented Software, by E. Gamma, R. Helm, R. Johnson, and J.
Vlissides. It is covered in a later module.)
Procedural functions (such as Cos and Sin) often use private constructors.
The Singleton pattern typically uses a private constructor. (The Singleton
pattern is also covered in Design Patterns: Elements of Reusable Object-
Oriented Software and in a later topic in this section.)
 Zero initialization is sometimes inappropriate.
Consider the compiler-generated default constructor for the following Date
class:
class Date
{
private int ccyy, mm, dd;
}

The default constructor will initialize the year field (ccyy) to zero, the month
field (mm) to zero, and the day field (dd) to zero. This might not be
appropriate if you want the date to default to a different value.
Topic Objective
To learn what to do if the
default constructor is
inappropriate.
Lead-in
Sometimes the compiler-
generated default
constructor will not be
appropriate. In these cases,
do not use it.
8 Module 9: Creating and Destroying Objects


 Invisible code is hard to maintain.
You cannot see the default constructor code. This can occasionally be a
problem. For example, you cannot single-step through invisible code when
debugging. Additionally, if you choose to use the default initialization to
zero, how will developers who need to maintain the code know that this
choice was deliberate?

Writing Your Own Default Constructor
If the compiler-generated default constructor is inappropriate, you must write
your own default constructor. The C# language helps you to do this.
You can write a constructor that only contains the code to initialize fields to
non-zero values. All fields that are not initialized in your constructor retain their
default initialization to zero. The following code provides an example:
class DefaultInit
{
public int a, b;
public DefaultInit( )
{
a = 42;
// b retains default initialization to zero
}
}
class Test
{
static void Main( )
{
DefaultInit di = new DefaultInit( );
Console.WriteLine(di.a); // Writes 42
Console.WriteLine(di.b); // Writes zero
}
}

You should be wary of doing more than simple initializations in your own
constructors. You must consider potential failure: the only sensible way you can
signal an initialization failure in a constructor is by throwing an exception.

The same is also true for operators. Operators are discussed in Module
12, “Operators, Delegates, and Events,” in Course 2124C, Programming
with C#.

When initialization succeeds, you have an object that you can use. If
initialization fails, you do not have an object.
Note

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

Đăng nhận xét