Tài liệu Module 8: Using Reference-Type Variables ppt

70 368 0
Tài liệu Module 8: Using Reference-Type Variables 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 Reference-Type Variables 2 Using Common Reference Types 15 The Object Hierarchy 23 Namespaces in the .NET Framework 29 Lab 8.1: Defining And Using Reference-Type Variables 35 Data Conversions 44 Multimedia: Type-Safe Casting 57 Lab 8.2: Converting Data 58 Review 63 Module 8: Using Reference-Type Variables 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 8: Using Reference-Type Variables iii Instructor Notes This module provides students with detailed information about reference types. It defines reference types and how they relate to classes. It explains the differences between reference-type and value-type variables. It explains the string type in detail as an example of a built-in reference type. This module also covers the System.Object class hierarchy and the object type in C#, showing the relationships between the various types. An overview of common namespaces in the Microsoft ® .NET Framework is provided. The module concludes by explaining how to convert data. It describes how to perform explicit conversions to treat data of one reference type like another. It also explains how to use boxing and unboxing conversions to convert data between reference and value types. After completing this module, students will be able to:  Describe the key differences between reference types and value types.  Use common reference types, such as string.  Explain how the object type works, and become familiar with the methods it supplies.  Describe common namespaces in the .NET Framework.  Determine whether different types and objects are compatible.  Explicitly and implicitly convert data types between reference types.  Perform boxing and unboxing conversions between reference and value data. Presentation: 90 Minutes Labs: 75 Minutes iv Module 8: Using Reference-Type Variables 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_08.ppt  Module 8, “Using Reference-Type Variables”  Lab 8.1, Defining and Using Reference-Type Variables  Lab 8.2, Converting Data  Multimedia presentation, Type-Safe Casting in C#, file 2124C_08a005.avi on the Student Materials compact disc. Preparation Tasks To prepare for this module, you should:  Read all of the materials for this module.  Complete the labs.  Read the instructor notes and margin notes for the module.  View the multimedia presentation. Multimedia Presentation Type-Safe Casting in C# C# is a type-safe language. This means that you can safely assign a value of one type to a variable of another type. This animation shows how casting affects what an object can and cannot do after it is cast as a different but related type. It also explains how to use the is operator to ensure that types that have been assigned are compatible.  To prepare for the multimedia presentation • To show this animation, double-click the file 2124C_08a005.avi. Module 8: Using Reference-Type Variables v Module Strategy Use the following strategy to present this module:  Using Reference-Type Variables Some of this material will be familiar to students. For example, they learned about the new keyword when discussing class instantiation. It is important that you explain the basic memory management of reference types in this section.  Using Common Reference Types You need to point out that reference types available in C# are part of the .NET Framework class library. This section explains that exceptions and strings are reference types, and provides some basic information about common methods of these types. Most of the material in this section relates to the string type and covers those methods that are likely to be of most use to students when they do the exercises in the labs.  The Object Hierarchy This section explains that every reference type inherits from object. You do not need to thoroughly discuss inheritance in this module because it is covered in detail in other modules, but you might need to explain the concept briefly if some of the students have not encountered it before. The Reflection topic might be difficult for less experienced students, as its value might not be immediately obvious. It is sufficient for you to explain that the mechanism exists and that a little more information is provided in Module 14, “Attributes,” in Course 2124C, Programming with C#.  Namespaces in the .NET Framework This is not intended to be a complete listing of everything in the .NET Framework. You need to stress that there are many useful features provided by .NET and that in this course you can only introduce students to some of the more interesting and valuable ones. When delivering the material, it is important that you demonstrate how to find information in the Microsoft Visual Studio ® .NET Help documents.  Data Conversions To understand the rules for converting reference types, students will need to have a basic knowledge of inheritance. Module 8: Using Reference-Type Variables 1 Overview  Using Reference-Type Variables  Using Common Reference Types  The Object Hierarchy  Namespaces in the .NET Framework  Data Conversions ***************************** ILLEGAL FOR NON-TRAINER USE****************************** In this module, you will learn how to use reference types in C#. You will learn about a number of reference types, such as string, that are built into the C# language and run-time environment. These are discussed as examples of reference types. You will also learn about the System.Object class hierarchy and the object type in particular, so you can understand how the various reference types are related to each other and to the value types. You will learn how to convert data between reference types by using explicit and implicit conversions. You will also learn how boxing and unboxing conversions convert data between reference types and value types. After completing this module, you will be able to:  Describe the important differences between reference types and value types.  Use common reference types, such as string.  Explain how the object type works and become familiar with the methods it supplies.  Describe common namespaces in the Microsoft® .NET Framework.  Determine whether different types and objects are compatible.  Explicitly and implicitly convert data types between reference types.  Perform boxing and unboxing conversions between reference and value data. Topic Objective To provide an overview of the module topics and objectives. Lead-in In this module, you will learn how to use reference types in C# and you will learn about the C# object hierarchy. 2 Module 8: Using Reference-Type Variables    Using Reference-Type Variables  Comparing Value Types to Reference Types  Declaring and Releasing Reference Variables  Invalid References  Comparing Values and Comparing References  Multiple References to the Same Object  Using References as Method Parameters ***************************** ILLEGAL FOR NON-TRAINER USE****************************** Reference types are important features of the C# language. They enable you to write complex and powerful applications and effectively use the run-time framework. After completing this lesson, you will be able to:  Describe the important differences between reference types and value types.  Use and discard reference variables.  Pass reference types as method parameters. Topic Objective To provide an overview of the topics covered in this section. Lead-in In this lesson, you will learn how to use reference types in C#. Delivery Tip Although there is some explanation of how memory is released from reference variables, this module does not contain a full discussion of garbage collection. Module 8: Using Reference-Type Variables 3 Comparing Value Types to Reference Types  Value types  The variable contains the value directly  Examples: char, int 42 42 int mol; mol = 42; int mol; mol = 42; • • string mol; mol = "Hello"; string mol; mol = "Hello"; Hello Hello  Reference types  The variable contains a reference to the data  Data is stored in a separate memory area ***************************** ILLEGAL FOR NON-TRAINER USE****************************** C# supports basic data types such as int, long and bool. These types are also referred to as value types. C# also supports more complex and powerful data types known as reference types. Value Types Value-type variables are the basic built-in data types such as char and int. Value types are the simplest types in C#. Variables of value type directly contain their data in the variable. Reference Types Reference-type variables contain a reference to the data, not the data itself. The data itself is stored in a separate memory area. You have already used several reference types in this course so far, perhaps without realizing it. Arrays, strings, and exceptions are all reference types that are built into the C# compiler and the .NET Framework. Classes, both built-in and user-defined, are also a kind of reference type. Topic Objective To compare value types to reference types. Lead-in Most values and variables that you have encountered so far in this course are value types. Here is a comparison between value types and reference types. Delivery Tip You might want to explain that reference types are not the same as reference parameters, despite the similarity in the names. It is probably also worth discussing why C# has value types at all: they are efficient and they are allocated on the stack. As a consequence of this, value types do not require garbage collection. Delivery Tip C and C++ developers might compare reference variables to pointers to objects. This is a helpful comparison, but point out that C# reference variables are completely type-safe and cannot point to invalid objects. Also, C and C++ do not have automatic garbage collection. 4 Module 8: Using Reference-Type Variables Declaring and Releasing Reference Variables  Declaring reference variables coordinate c1; c1 = new coordinate(); c1.x = 6.12; c1.y = 4.2; coordinate c1; c1 = new coordinate(); c1.x = 6.12; c1.y = 4.2; • • 6.12 6.12 4.2 4.2 c1 = null; c1 = null; • • 6.12 6.12 4.2 4.2  Releasing reference variables ***************************** ILLEGAL FOR NON-TRAINER USE****************************** To use reference-type variables, you need to know how to declare and initialize them and how to release them. Declaring Reference Variables You declare reference-type variables by using the same syntax that you use when declaring value-type variables: coordinate c1; The preceding example declares a variable c1 that can hold a reference to an object of type coordinate. However, this variable is not initialized to reference any coordinate objects. To initialize a coordinate object, use the new operator. This creates a new object and returns an object reference that can be stored in the reference variable. coordinate c1; c1 = new coordinate( ); If you prefer, you can combine the new operator with the variable declaration so that the variable is declared and initialized in one statement, as follows: coordinate c1 = new coordinate( ); After you have created an object in memory to which c1 refers, you can then reference member variables of that object by using the dot operator as shown in the following example: c1.x = 6.12; c1.y = 4.2; Topic Objective To show how reference variables are declared and initialized. Lead-in To use reference-type variables, you need to know how to declare and initialize them and how to release them. For Your Information In C and C++, you need to use a special ->operator to remove a reference to a pointer and access a member. There is no analogous requirement in C#. [...]... operators (, =) to compare whether two variables are referring to the object 10 Module 8: Using Reference-Type Variables Multiple References to the Same Object Topic Objective To show that two reference variables can refer to the same object Two references can refer to the same object Lead-in Two ways to access the same object for read/write Because variables of reference type hold a reference... (or simply allow the reference to go out of scope) 6 Module 8: Using Reference-Type Variables Invalid References Topic Objective To explain how the compiler and run-time system handle invalid references Lead-in You cannot access member variables or methods if the reference is not valid If you have invalid references You cannot access members or variables Invalid references at compile time Compiler... null) c1.x = 45; else Console.WriteLine("c1 has a null value"); 8 Module 8: Using Reference-Type Variables Comparing Values and Comparing References Topic Objective To show the default implementation of the == and != operators for reference variables Lead-in The == and != operators might not work in the way you expect for reference variables Comparing value types == and != compare values Comparing... compares the value of the strings Module 8: Using Reference-Type Variables For Your Information C and C++ have similar semantics for pointer comparison Visual Basic uses the Is operator to compare two references Delivery Tip You might want to mention that you can write a valuecomparison version of == by using operator overloading However, that topic is not covered in this module Delivery Tip It might surprise.. .Module 8: Using Reference-Type Variables 5 Example of Declaring Reference Variables Classes are reference types The following example shows how to declare a user-defined class called coordinate For simplicity, this class has only two public member variables: x and y class coordinate { public double x = 0.0; public double y... c2.y); The output of this program is as follows: 2.3 , 7.6 2.3 , 7.6 Assigning c2 to c1 copies the reference so that both variables are referencing the same instance Therefore, the values printed for the member variables of c1 and c2 are the same Module 8: Using Reference-Type Variables 11 Writing and Reading the Same Data Through Different References In the following example, an assignment has been... reference and read the same data through another reference 12 Module 8: Using Reference-Type Variables Using References as Method Parameters Topic Objective To show that references can be passed to and from methods in various ways References can be used as parameters When passed by value, data being referenced may be changed 23 23 Lead-in Reference variables can be passed in and out of a method 34 34 ••... reference comparisons (the == and != operators) 28 Module 8: Using Reference-Type Variables The typeof Operator At compile time, you can use the typeof operator to return the type information from a given type name The following example retrieves run-time type information for the type byte, and displays the type name to the console using System; using System.Reflection; Type t = typeof(byte); Console.WriteLine("Type:... *****************************ILLEGAL FOR NON-TRAINER USE****************************** A number of reference-type classes are built in to the C# language After completing this lesson, you will be able to: Describe how built-in classes work Use built-in classes as models when creating your own classes 16 Module 8: Using Reference-Type Variables Exception Class Topic Objective To review the Exception class Lead-in Exception... Console.WriteLine(sText.ToUpper( )); // HOW TO SUCCEED Console.WriteLine(sText.ToLower( )); // how to succeed 20 Module 8: Using Reference-Type Variables String Comparisons Topic Objective To describe the comparison operators that are used with strings Lead-in You can use the == and != operators on string variables to compare string contents Equals method Value comparison Compare method More comparisons Case-insensitive . 2124C_08a005.avi. Module 8: Using Reference-Type Variables v Module Strategy Use the following strategy to present this module:  Using Reference-Type Variables. knowledge of inheritance. Module 8: Using Reference-Type Variables 1 Overview  Using Reference-Type Variables  Using Common Reference Types 

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

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan