Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 56 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
56
Dung lượng
0,91 MB
Nội dung
Module 2: Overview of C# Contents Overview Structure of a C# Program Basic Input/Output Operations Recommended Practices 15 Compiling, Running, and Debugging 22 Lab 2.1: Creating a Simple C# Program 36 Review 44 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 2: Overview of C# Instructor Notes Presentation: 60 Minutes Lab: 60 Minutes This module introduces students to the C# programming language Students will learn about the essential elements of a basic C# program Good programming practices and style will also be covered Finally, students will learn how to use Microsoft® Visual Studio® to edit, compile, execute, and debug a C# program After completing this module, students will be able to: Explain the structure of a simple C# program Use the Console class of the System namespace to perform basic input/output operations Handle exceptions in a C# program Generate Extensible Markup Language (XML) documentation for a C# program Compile, link, and execute a C# program Use the Visual Studio Debugger to trace C# program execution 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_02.ppt Module 2, “Overview of C#” Lab 2, Creating a Simple C# Program Preparation Tasks To prepare for this module, you should: Read all of the materials for this module Complete the lab Practice using Visual Studio NET Practice the demonstrations iii iv Module 2: Overview of C# Demonstrations This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes Using Visual Studio to Create a C# Program In this demonstration, you will create a C# console application by using Visual Studio NET To create a C# application Start Visual Studio NET On the File menu, point to New, and then click Project In the New Project dialog box, provide the information shown in the following table, and then click OK Element Value Project Type (tree view) Visual C# Projects Templates (icon) Console Application Name Hello Location C:\temp When the project has been generated, point out and discuss the following features of Visual Studio: • The Solution Explorer window i Close the Class1.cs code window ii Change the name of Class1.cs to Hello.cs iii Double-click Hello.cs to redisplay the code window • The Properties window • The toolbars • The View menu • The Build menu • The Debug menu • The Help menu Module 2: Overview of C# v Using the code window displaying Hello.cs, point out and discuss the following: • The Hello namespace Mention that namespaces will be discussed later You could delete this line and the corresponding braces, but leave them intact for now • The using directive • The XML comments Use this section to provide a brief description of the program Comments will be covered more fully later • The class definition The default name for the class is Class1 Change it to Demonstrator • The Main method Insert the following code: Console.WriteLine("Hello, World"); ã Microsoft IntelliSenseđ On the File menu, click Save All Exit Visual Studio Generating and Viewing XML Documentation In this demonstration, you will show students how to compile the XML comments that are embedded in a C# program into an XML file, and how to view the documentation that is generated by using Microsoft Internet Explorer To compile XML comments and generate an XML file From the Microsoft Windows® Start button, point to All Programs, then click Visual Studio NET, then click on Visual Studio NET Tools, and then click Visual Studio NET Command Prompt Go to the install folder\Democode\Mod02\XML Demo folder Use WordPad to view the Hello2.cs file Discuss the XML comments in this program Return to the Command window Compile the program, and generate the XML documentation by using the following code: csc /doc:Hello2.xml Hello2.cs At the command prompt, type the following: Hello2.xml Internet Explorer will start and display the XML file Exit Internet Explorer when finished vi Module 2: Overview of C# Compiling and Running a C# Program In this demonstration, you will show how to compile and run a C# program by using Visual Studio You will also show how to locate and correct compile-time errors To compile a C# program by using Visual Studio NET Start Visual Studio NET On the File menu, point to Open, and then click Project Open the install folder\Democode\Mod02\Converter\Converter.sln project On the Build menu, click Build Solution The program contains two syntax errors Two error messages will appear in the Task List In the Task List, double-click the first error You will be taken to the line containing the first error in the program (a missing “.” between Console and ReadLine) Correct the error In the Task List, double-click the second error You will be taken to the line containing the second error in the program (the variable degreesCelsius spelled incorrectly as degreesCelcius) Correct the error On the File menu, click Save All 10 On the Build menu, click Build Solution The program will compile without errors To run the C# program from Visual Studio On the Debug menu, click Start Without Debugging A console window containing the prompt “Please give me a temperature in degrees F:” will appear Type the value 212 and then press ENTER The message “212 degrees F is 100 degrees C” will appear Press any key to close the program Module 2: Overview of C# vii Using ILDASM In this demonstration, you will show how to use Intermediate Language Disassembler (ILDASM) to examine the manifest and Microsoft Intermediate Language (MSIL) code in a class To use ILDASM to examine a class From the Windows Start button, point to Programs, then click Visual Studio NET, then click Visual Studio NET Tools, and then click Visual Studio NET Command Prompt Go to the install folder\Democode\Mod02\Converter\bin\Debug folder Type the following: ildasm Converter.exe ILDASM will display a window containing a tree structure Expand the Converter node A component named ConvertIt will appear Point out that this is the class that was presented in the previous demonstration Expand the ConvertIt node The methods, constructors, and other items that make up the class will be displayed On the View menu, click Show source lines Double-click the Main method A window containing the MSIL instructions for the Main method will appear a Scroll through the window to show all of the MSIL instructions and the C# source code b Close the window Double-click MANIFEST A window showing the manifest (contents) of the module and its references will appear Close the window Close the ILDASM window viii Module 2: Overview of C# Using the Visual Studio Debugger In this demonstration, you will debug a C# program by using the Visual Studio NET debugger to set breakpoints and watches You will step through code to examine the values of variables Please note that the demonstration Compiling and Running a C# Program must already have been completed This C# program, which converts temperatures from Fahrenheit to Celsius, contains a bug that causes incorrect temperature conversion results under some circumstances You will find and correct the problem To run the C# program Open the Converter project, which is located in the install folder\DemoCode\Mod02\Converter folder Run the program by clicking Start Without Debugging on the Debug menu or by pressing CTRL+F5 Explain that the program prompts the user for a temperature in degrees Fahrenheit It converts the user input to an integer and stores it in the degreesFahrenheit variable It then calculates the equivalent Celsius temperature by using the standard conversion formula and stores the result in the degreesCelsius variable The program finally displays the original Fahrenheit temperature in addition to the calculated Celsius value Type 32 at the temperature prompt Note for the students that the program converts this to degrees Celsius, which is correct Run the program again, and type a value of 212 at the prompt This is the boiling point of water Note for the students that the program displays the result as 100 degrees Celsius, which is also correct Run the program a third time, and type a temperature of 75 degrees at the prompt Note for the students that the result displayed is 23 degrees Celsius This is inaccurate because 75 degrees Fahrenheit is 23.8889 degrees Celsius Explain that the program seems to be truncating the result to an integer To identify the bug in the C# program by setting a breakpoint and by using the Watch window Set a breakpoint just after the program has read in the Fahrenheit temperature Run the program in debug mode by clicking Start on the Debug menu or by pressing F5 Type 75 and press ENTER The program reaches the breakpoint and stops Display the Watch window, and add the degreesFahrenheit and degreesCelsius variables to the list of watched variables Explain that you can monitor the values of variables in the Watch window Module 2: Overview of C# ix Run the program one line at a time from the breakpoint by clicking Step Over on the Debug menu or by pressing F10 This is called single-stepping The next line of code is executed, and then the program stops Any changes made to the variables are shown in the Watch window For example, the value of degreesFahrenheit is now shown as 75 When you step over the next line, the degreesCelsius variable is updated with its calculated value of 23.0 This is the line that contains the bug The problem is that an integer calculation is being performed on integer data before being assigned to a floating-point variable Rounding errors are accumulating and producing an inaccurate result Finish program executing by pressing F5 To fix the bug in the C# program and verifying the fix Change a constant to a floating-point value by changing 32 to 32F to force the compiler to perform a floating-point calculation Build and Run the program again Click Step Over on the Debug menu to see the results of the change Notice that value of degreesCelsius in the Watch window is now 23.8889 Press F10 to continue stepping through the program Click Continue on the Debug menu, and the program will run until it is finished x Module 2: Overview of C# Module Strategy Use the following strategy to present this module: Structure of a C# Program Describe the basic structure of a C# program Point out that a C# application is a collection of one or more classes, and that each class has one or more methods The entry point to the program is the Main method, which can occur in any class in the application (but which should occur in only one) Discuss how an application can use pre-written classes that were written by other developers, and mention that the common language runtime provides a set of numerous classes that perform a wide variety of functions Inform students that classes can be organized into namespaces (mention the System namespace), and that the using directive allows the programmer to abbreviate the full names of classes Basic Input/Output Operations Explain that C# has no I/O capability of its own, but relies instead on classes and methods in System and other namespaces Describe the Console class, the standard input, standard output, and standard error streams, and how Console provides access to these streams by using the Write, WriteLine, Read, and ReadLine methods Recommended Practices Point out that good program layout and comments are important if a program is to be maintainable Also explain the importance of exception handling—you never know when an exceptional circumstance could occur It is easier to design exception handling into a program at the start than to try to add it later Compiling, Running, and Debugging Describe and demonstrate how to compile and run a C# program from the command line and from within Visual Studio Explain the Just-in-Time (JIT) compiler and options Show how to use the Visual Studio Debugger to debug a C# program Finish by briefly cataloging the tools that are supplied with the software development kit (SDK) ... finished x Module 2: Overview of C# Module Strategy Use the following strategy to present this module: Structure of a C# Program Describe the basic structure of a C# program Point out that a C# application... supplied with the software development kit (SDK) Module 2: Overview of C# Overview Topic Objective To provide an overview of the module topics and objectives Lead-in In this module, you will learn... building blocks of a C# program 4 Module 2: Overview of C# The Class Topic Objective To point out that every C# application is a collection of classes A C# application is a collection of classes,