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

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

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Contents Overview 1 Using Constructors 2 Initializing Data 13 Lab 9.1: Creating Objects 32 Objects and Memory 40 Resource Management 46 Lab 9.2: Managing Resources 55 Review 58 Module 9: Creating and Destroying Objects 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. Module 9: Creating and Destroying Objects iii Instructor Notes This module provides students with the theory and syntax for creating and destroying objects in a C# application. After completing this module, students will be able to:  Create objects by using the new operator.  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.  Inherit from IDisposable interface and implement Dispose method. 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_09.ppt  Module 9, “Creating and Destroying Objects”  Lab 9.1, Creating Objects  Lab 9.2, Managing Resources Preparation Tasks To prepare for this module, you should:  Read all of the materials for this module.  Complete the labs. Presentation: 90 Minutes Labs: 75 Minutes iv Module 9: Creating and Destroying Objects Module Strategy Use the following strategy to present this module:  Using Constructors Creating Objects. Explain how allocation from the heap works, and explain why it is normally very fast but occasionally slow. Mention garbage collection, but do not provide details: you will have plenty of opportunity to discuss this further in the second section. The notes emphasize that you can only acquire memory by using the new keyword; the string and array syntax is just shorthand (as is the newInstance method of the class class). Explain how to use constructors to perform initialization. If there are any C++ programmers in the class, emphasize that although you can separate allocation and initialization in C++, you cannot separate them in C#. This section focuses on instance constructors. Static constructors are mentioned in the next section. Using the Default Constructor. This topic provides a detailed explanation of the constructor that the compiler writes for you if you do not write one yourself. Clarify that this applies only for classes and not for structs, but do not spend too much time on struct rules. (There is a separate topic about these rules later in this module.) It is worth mentioning that constructors have no return type. You might want to ask the class how a constructor signals that it has failed to initialize. Overriding the Default Constructor. The purpose of the example on the slide is to show that the default zero values of ccyy, mm, and dd in the compiler- generated default constructor are inappropriate. The Gregorian calendar started with year 1, January is considered month 1, and days also start with 1. There are also some other points worth mentioning. For example, you might want to mention public access, but do not spend too much time discussing it, since that will be covered in a later topic. The message is that if the compiler-generated code is inappropriate, then do not use it. Write your own. Overloading Constructors. Constructors are simply methods. Methods can be overloaded, so constructors can also be overloaded. There are some interesting points in the notes for this topic relating to the Whole Value pattern. You might want to discuss these points in class. Mention the last bullet point explicitly. If you write a class constructor, the compiler no longer generates the default constructor. 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 You cannot use the this keyword in an expression to create a constructor argument The following code provides an example: class Point { // Compile-time error public Point( ) : this(X(this), Y(this)) { } public Point(int x, int y) { } private static int X(Point p) { } private static int Y(Point p) { } } 17 18 Module 9: Creating and Destroying Objects. .. Overload class, and both are called in Use.Main There is no ambiguity, because the number and types of the arguments determine which method is called 10 Module 9: Creating and Destroying Objects Initializing an Object in More Than One Way The ability to initialize an object in different ways was one of the primary motivations for allowing overloading Constructors are special kinds of methods, and they can... dd, mm, and ccyy on the left side of the three initializations This is not extensive duplication, but it is duplication nonetheless, and you should avoid it if possible For example, suppose you decided to change the representation of a Date to one long field You would need to rewrite every Date constructor Module 9: Creating and Destroying Objects 15 Refactoring Duplicate Initializations A standard... 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 Module 9: Creating and Destroying Objects 9 Overloading Constructors Topic Objective To introduce the idea that you can overload constructors to provide more than one way to initialize objects. .. have seen the basic elements of constructors Constructors also have a number of additional features and uses After completing this lesson, you will be able to: Initialize the data in objects by using constructors Use private constructors Use static constructors 14 Module 9: Creating and Destroying Objects Using Initializer Lists Topic Objective To show how to use initializer lists to avoid constructor... such as C and in hybrid languages such as C++, but they are not allowed in C# In C#, functions must be declared inside a class or struct, as follows: class Math { public double Cos(double x) { } public double Sin(double x) { } } Module 9: Creating and Destroying Objects 27 Declaring Static vs Instance Methods The problem with the technique in the preceding example is that, because Cos and Sin are... the single instance, and this instance is then used to call instance methods Module 9: Creating and Destroying Objects 29 Using Static Constructors Topic Objective To introduce the concept of static constructors and to explain how to use them Lead-in All the constructors covered so far have been constructors that initialize objects These are called instance constructors There is one other kind of constructor... 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 6 Module 9: Creating and Destroying Objects Features of a Default Constructor... 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 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... if you try to refactor the initialization of a readonly field (This is covered later in this module. ) Object-oriented programming languages provide mechanisms to help solve this known problem For example, in C++ you can use default values In C# you use initializer lists 16 Module 9: Creating and Destroying Objects Using an Initializer List An initializer list allows you to write a constructor that . 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. 9.1: Creating Objects 32 Objects and Memory 40 Resource Management 46 Lab 9.2: Managing Resources 55 Review 58 Module 9: Creating and Destroying Objects

Ngày đăng: 17/01/2014, 09:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan