1. Trang chủ
  2. » Công Nghệ Thông Tin

c# 2010 for programmers

1,2K 14K 1
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề C# 2010 for Programmers
Tác giả Paul Deitel, Harvey Deitel
Trường học Deitel & Associates, Inc.
Chuyên ngành Programming / Computer Science
Thể loại Sách giáo trình
Năm xuất bản 2010
Thành phố Upper Saddle River, NJ
Định dạng
Số trang 1.239
Dung lượng 34,61 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Tài liệu học lập trình C# cho sinh viên và mọi người.

Trang 3

been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty

of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential

damages in connection with or arising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales,

which may include electronic versions and/or custom covers and content particular to your business, training goals,

marketing focus, and branding interests For more information, please contact:

U S Corporate and Government Sales

Visit us on the Web: informit.com/ph

Library of Congress Cataloging-in-Publication Data

On file

© 2011 Pearson Education, Inc.

All rights reserved Printed in the United States of America This publication is protected by copyright, and permission

must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or

transmis-sion in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information

re-garding permissions, write to:

Pearson Education, Inc.

Rights and Contracts Department

501 Boylston Street, Suite 900

Boston, MA 02116

Fax (617) 671-3447

ISBN-13: 978-0-13261820-5

ISBN-10: 0-13-261820-6

Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana

First printing, October 2010

Trang 4

Deitel & Associates, Inc.

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Capetown • Sydney • Tokyo • Singapore • Mexico City

Trang 5

Microsoft, Windows, Silverlight, SQL Server, Visual Studio, Visual Basic, Visual C# and Visual Web

Developer are either registered trademarks or trademarks of Microsoft Corporation in the United States

and/or other countries.

Trang 7

ptg

Trang 8

2.6 Using Visual Programming to Create a Simple Program that

Trang 9

3.3 Creating a Simple Application in Visual C# Express 46

3.5 Formatting Text with Console.Write and Console.WriteLine 56

4.2 Classes, Objects, Methods, Properties and Instance Variables 67

4.3 Declaring a Class with a Method and Instantiating an Object of a Class 68

4.7 Software Engineering with Properties and set and get Accessors 81

Trang 10

7.9.2 Random-Number Repeatability for Testing and Debugging 166

7.10 Case Study: A Game of Chance (Introducing Enumerations) 167

8.5 Case Study: Card Shuffling and Dealing Simulation 199

8.9 Case Study: Class GradeBook Using an Array to Store Grades 212

8.11 Case Study: GradeBook Using a Rectangular Array 222

Trang 11

9.3 Querying an Array of Employee Objects Using LINQ 238

10.4 Referring to the Current Object’s Members with the this Reference 255

10.13 Time Class Case Study: Creating Class Libraries 277

11.4 Relationship between Base Classes and Derived Classes 305

11.4.1 Creating and Using a CommissionEmployee Class 305

11.4.2 Creating a BasePlusCommissionEmployee Class without

11.4.3 Creating a CommissionEmployee–BasePlusCommissionEmployee

11.4.4 CommissionEmployee–BasePlusCommissionEmployee Inheritance

Hierarchy Using protected Instance Variables 319

11.4.5 CommissionEmployee–BasePlusCommissionEmployee Inheritance

Hierarchy Using private Instance Variables 323

Trang 12

12.5.2 Creating Concrete Derived Class SalariedEmployee 345

12.5.3 Creating Concrete Derived Class HourlyEmployee 346

12.5.4 Creating Concrete Derived Class CommissionEmployee 348

12.5.5 Creating Indirect Concrete Derived Class

12.5.6 Polymorphic Processing, Operator is and Downcasting 351

12.5.7 Summary of the Allowed Assignments Between Base-Class

12.7.4 Modifying Class Employee to Implement Interface IPayable 362

12.7.5 Modifying Class SalariedEmployee for Use with IPayable 363

12.7.6 Using Interface IPayable to Process Invoices and Employees

13.2 Example: Divide by Zero without Exception Handling 373

13.3 Example: Handling DivideByZeroExceptions and FormatExceptions 376

13.4.2 Determining Which Exceptions a Method Throws 382

Trang 13

14.3.3 Delegates and the Event-Handling Mechanism 407

Trang 14

16.11 Length and Capacity Properties, EnsureCapacity Method and

16.12 Append and AppendFormat Methods of Class StringBuilder 521

16.13 Insert, Remove and Replace Methods of Class StringBuilder 523

16.15.1 Simple Regular Expressions and Class Regex 529

16.15.3 Validating User Input with Regular Expressions and LINQ 535

17.9 Creating a Sequential-Access File Using Object Serialization 576

17.10 Reading and Deserializing Data from a Binary File 580

18.5.2 Data Bindings Between Controls and the LINQ to SQL Classes 595

Trang 15

18.6.1 Creating the Display Query Results GUI 600

18.6.2 Coding the Display Query Results Application 600

18.9.1 Creating the Address Book Application’s GUI 615

19.4.2 Examining WebTime.aspx’s Code-Behind File 636

19.7.3 Options.aspx: Selecting a Programming Language 652

19.7.4 Recommendations.aspx: Displaying Recommendations

19.8.1 Building a Web Form that Displays Data from a Database 659

19.8.2 Modifying the Code-Behind File for the Guestbook Application 662

19.10 Case Study: Password-Protected Books Database Application 664

Trang 16

21.7.2 Binary Search Tree of IComparable Objects 723

Trang 17

24.14 Defining a Control’s Appearance with Control Templates 826

26.4 Extensible Stylesheet Language and XSL Transformations 893

Trang 18

Contents xvii

27.2.4 Modifying the Default.aspx and About.aspx Pages 930

27.2.5 Creating a Content Page That Only Authenticated

27.2.6 Linking from the Default.aspx Page to the Books.aspx Page 932

27.2.8 Customizing the Password-Protected Books.aspx Page 935

27.3.5 Using Controls from the Ajax Control Toolkit 944

28.6 Publishing and Consuming SOAP-Based WCF Web Services 952

28.6.5 Creating a Client to Consume the WelcomeSOAPXMLService 956

28.7 Publishing and Consuming REST-Based XML Web Services 960

28.7.2 Creating a REST-Based XML WCF Web Service 960

28.7.3 Consuming a REST-Based XML WCF Web Service 963

28.8 Publishing and Consuming REST-Based JSON Web Services 964

28.8.1 Creating a REST-Based JSON WCF Web Service 964

28.8.2 Consuming a REST-Based JSON WCF Web Service 966

28.9 Blackjack Web Service: Using Session Tracking in a

28.10 Airline Reservation Web Service: Database Access and

28.11 Equation Generator: Returning User-Defined Types 986

28.11.1 Creating the REST-Based XML EquationGenerator Web Service 989

28.11.2 Consuming the REST-Based XML EquationGenerator Web Service 990

Trang 19

29.4 Building a Silverlight WeatherViewer Application 1002

29.4.2 Obtaining and Displaying Weather Forecast Data 1007

29.6.1 Getting Started With Deep Zoom Composer 1027

29.6.2 Creating a Silverlight Deep Zoom Application 1030

30.3 Identifying the Classes in the ATM Requirements Document 1053

31.2 Starting to Program the Classes of the ATM System 1088

31.3 Incorporating Inheritance and Polymorphism into the ATM System 1093

Trang 20

D.2 Abbreviating Binary Numbers as Octal and Hexadecimal Numbers 1136

D.3 Converting Octal and Hexadecimal Numbers to Binary Numbers 1137

D.4 Converting from Binary, Octal or Hexadecimal to Decimal 1137

D.5 Converting from Decimal to Binary, Octal or Hexadecimal 1138

D.6 Negative Binary Numbers: Two’s Complement Notation 1140

Trang 21

G.5 Controlling Execution Using the Step Into, Step Over, Step Out

Trang 22

“Live in fragments no longer, only connect.”

—Edgar Morgan Forster

Welcome to Visual C#® 2010, C# 4 and the world of Microsoft® Windows® and Internet

and web programming with Microsoft’s NET 4 Framework! This book presents

leading-edge computing technologies for professional software developers We believe the book

will give you an informative, challenging and entertaining C# educational experience

We use the Deitel signature live-code approach, presenting most concepts in the

con-text of complete working Visual C# 2010 programs, rather than using code snippets Each

code example is immediately followed by one or more sample executions All the source

code is available at www.deitel.com/books/csharpfp4/

At Deitel & Associates, we author programming-language professional books,

Live-Lessons video courses and textbooks under the Prentice Hall imprint of Pearson Higher

Education, and deliver our Dive Into® Series professional instructor-led training courses

worldwide on site at corporations, government agencies, branches of the military and

aca-demic institutions

As you read the book, if you have questions, send an e-mail to deitel@deitel.com;

we’ll respond promptly For updates on this book and its supporting Visual C# software,

visit www.deitel.com/books/csharpfp4/, follow us on Twitter (@deitel) and Facebook

(www.deitel.com/deitelfan), and subscribe to the Deitel® Buzz Online newsletter

(www.deitel.com/newsletter/subscribe.html) Check out our growing list of C# and

related Resource Centers at www.deitel.com/ResourceCenters.html

New and Updated Features

Here are some key features of C# 2010 for Programmers, 4/e:

LINQ LINQ provides a uniform syntax for querying data Strong typing enables

Visual Studio to provide IntelliSense support for LINQ operations and results.

LINQ can be used on different types of data sources, including collections and files

(LINQ to Objects, Chapters 9 and 17, respectively), databases (LINQ to SQL,

Chapters 18, 19, 27 and 28) and XML (LINQ to XML, Chapters 26 and 29)

Early Introduction to Generic Collections and LINQ We introduce LINQ early

so that you can begin using it with arrays To enable you to work with more

flex-ible data structures throughout the book, we introduce the List generic

collec-tion—a dynamic data structure—in close proximity to arrays This enables us to

demonstrate the power of LINQ and how it can be applied to most data

struc-tures As a generic collection, the List class provides strong compile-time type

safety—ensuring that all elements of the collection are of the appropriate type

Preface

Trang 23

Databases We use the free Microsoft SQL Server Express Edition and real-world

applications to present the fundamentals of database programming Chapters 18,

27 and 28 discuss database and LINQ to SQL fundamentals, presented in the

context of an address-book desktop application, a web-based bookstore

applica-tion and a web-based airline reservaapplica-tion system Chapter 18 also demonstrates

us-ing the Visual Studio 2010 tools to build a GUI application that accesses a

database using LINQ to SQL

Windows Presentation Foundation (WPF) GUI and Graphics We begin our

GUI discussion with the traditional Windows Forms controls in Chapters 14–

15 We extend our coverage in Chapters 24 and 25 with an introduction to

Win-dows Presentation Foundation (WPF)—Microsoft’s framework that integrates

GUI, graphics and multimedia capabilities We present many examples,

includ-ing a paintinclud-ing application, a text editor, a color chooser, a book-cover viewer, a

television video player, a 3-D rotating pyramid and various animations

Windows Communication Foundation (WCF) Web Services Microsoft’s NET

strategy embraces the Internet and web as integral to software development and

deployment Web-services technology enables information sharing, e-commerce

and other interactions using standard Internet protocols and technologies, such as

Hypertext Transfer Protocol (HTTP), Extensible Markup Language (XML),

Simple Object Access Protocol (SOAP) and REST (Representational State

Trans-fer) Web services enable you to package application functionality in a manner

that turns the web into a library of reusable software components We replaced

our treatment of ASP.NET web services from an earlier edition with a discussion

of Windows Communication Foundation (WCF) services in Chapter 28 WCF

is a set of technologies for building distributed systems in which system

compo-nents communicate with one another over networks WCF uses a common

framework for all communication between systems, so you need to learn only one

programming model Chapter 28 focuses on WCF web services that use either the

SOAP protocol or REST architecture The REST examples transmit both XML

(eXtensible Markup Language) and JSON (JavaScript Object Notation)

ASP.NET 4 and ASP.NET AJAX The NET platform enables you to create

ro-bust, scalable web-based applications Microsoft’s NET server-side technology,

ASP.NET 4, allows you to build web documents that respond to client requests

To enable interactive web pages, server-side programs process information that

users input into HTML forms ASP.NET provides enhanced visual programming

capabilities, similar to those used in building Windows Forms for desktop

pro-grams You can create web pages visually, by dragging and dropping web controls

onto web forms Chapters 19 and 27 introduce these powerful technologies We

present a sequence of examples in which you build several web applications,

includ-ing a web-based bookstore Chapter 27 culminates with an example that

demon-strates the power of AJAX We also discuss the ASP.NET Development Server

(which enables you to test your web applications on your local computer), multitier

architecture and web transactions The chapter uses ASP.NET 4 and LINQ to

build a guestbook application that retrieves information from a database and

dis-plays it in a web page We use a LinqDataSource from a web application to

Trang 24

New and Updated Features xxiii

ulate a database We use ASP.NET AJAX controls to add AJAX functionality to

web applications to improve their responsiveness—in particular, we use the

UpdatePanel control to perform partial-page updates

Silverlight In Chapter 29, we introduce Silverlight, Microsoft’s technology for

building Rich Internet Applications (RIA) Silverlight, a competitor to JavaFX

and Adobe’s Flash and Flex technologies, allows you to create visually stunning,

multimedia-intensive user interfaces for web applications using NET languages

such as Visual C# Silverlight is a subset of WPF that runs in a web browser using

a plug-in One of Silverlight’s most compelling features is its ability to stream

high-definition video The chapter presents powerful multimedia applications,

including a weather viewer, Flickr® photo viewer, deep zoom book-cover collage

and video viewer

Language Features to Support LINQ Many of the Visual C# language features

we cover in Chapter 10 were introduced to support LINQ We show how to use

extension methods to add functionality to a class without modifying the class’s

source code We use delegates (objects that hold method references) to support

our discussion of lambda expressions, which define anonymous functions

Lamb-da expressions can be used wherever delegates are needed—typically as arguments

to method calls or to help create more powerful LINQ queries You’ll see how to

use anonymous types to create simple classes that store data without writing a class

definition—a feature used frequently in LINQ

Implicitly Typed Local Variables When you initialize a local variable in its

decla-ration, you can omit the variable’s type—the compiler infers it from the type of

the initializer value (introduced in Chapter 9) This is another feature used

fre-quently in LINQ

Object and Collection Initializers When creating an object, you can use the object

initializer syntax (introduced in Chapter 9) to assign values to the new object’s

properties Similarly, you can use the collection initializer syntax (Chapter 9) to

specify values for the elements of collections, just as you do with arrays

Auto-Implemented Properties For cases in which a property of a class has a get

accessor that simply returns a private instance variable’s value and a set accessor

that simply assigns a value to the instance variable, C# provides automatically

im-plemented properties (also known as auto-imim-plemented properties; introduced in

Chapter 4) With an auto-implemented property, the compiler automatically

cre-ates a private instance variable and the get and set accessors for manipulating

it This gives you the software engineering benefits of having a property, but

en-ables you to implement the property trivially

Other New Language Features We cover optional parameters, named

parame-ters, covariance and contravariance

Visual C# 2010 Express IDE All screenshots have been updated to the Visual C#

2010 Express IDE

Contextual keywords The keywords table (Chapter 3) includes the contextual

keywords—words that are considered keywords only in certain contexts Outside

those contexts, such keywords can still be used as valid identifiers This minimizes

Trang 25

the chance that older Visual C# code will break when upgrading to Visual C#

2010 Many of these contextual keywords are used with LINQ

IntelliSense We point out additional ways in which the IDE’s IntelliSense helps

you write code

Data Tips and Visualizers We use DataTips and visualizers to view object

con-tents in the code window during debugging

Tuned Treatment of Object-Oriented Programming The book offers a rich

treat-ment of C#’s object-oriented programming features Chapter 4 introduces how to

create classes and objects These concepts are extended in Chapter 10 Chapter 11

discusses how to create powerful new classes quickly by using inheritance to

“ab-sorb” the capabilities of existing classes Chapter 12 presents the crucial concepts

of polymorphism, abstract classes, concrete classes and interfaces, all of which

fa-cilitate powerful manipulations among objects in an inheritance hierarchy

Visual Studio 2010 Debugger In Appendix G, we explain how to use key

debug-ger features, such as setting “breakpoints” and “watches” and stepping into and

out of methods Most of the material in this appendix can be covered after

Chapter 4 One example uses the conditional AND (&&) operator, which is

ex-plained in Chapter 6

Case Studies

Among the hundreds of complete working C# programs we present are many case studies,

including:

• GradeBook class in Chapters 4–8

• OOD/UML ATM system in Chapters 30 and 31

• Time class in Chapter 10

• Employee payroll application in Chapters 11–12

• WPF painter application in Chapter 24

• WPF text-editor application in Chapter 24

• WPF color-chooser application in Chapter 24

• WPF book cover viewer application in Chapter 24

• WPF television application in Chapter 25

• Address-book application in Chapter 18

• Guestbook ASP.NET application in Chapter 19

• Password-protected books database ASP.NET application in Chapter 27

• Airline reservation web service in Chapter 28

• Blackjack web service in Chapter 28

• Equation-generator web service and math-tutor application in Chapter 28

• Silverlight weather-viewer application in Chapter 29

• Silverlight Flickr® photo-viewer application in Chapter 29

• Silverlight Deep Zoom book-cover collage application in Chapter 29

• Silverlight video-viewer application in Chapter 29

Trang 26

Object-Oriented Design Case Study: Designing and Implementing an ATM xxv

Object-Oriented Design Case Study:

Designing and Implementing an ATM

In this case study, we design and fully implement the software for a simple automated teller

machine (ATM) After completing this case study, you’ll be familiar with an

object-orient-ed design and implementation for a significant C# application

The design was developed at Deitel & Associates, Inc., and reviewed by industry

pro-fessionals and academics We kept the design and the code small and simple so that they

would work well in C# professional courses

The Unified Modeling Language® (UML®) has become the preferred graphical

mod-eling language for designing object-oriented systems Chapters 30 and 31 present a

care-fully paced introduction to object-oriented design using the UML

We employ a carefully developed, incremental object-oriented design process to

pro-duce a UML model for our ATM system From this design, we propro-duce a substantial

working C# implementation using key programming notions, including classes, objects,

encapsulation, visibility, composition, inheritance and polymorphism

Here’s what the sections of the case study cover:

Section 1.9—Introduction to Object Technology—presents basic concepts and

ter-minology of object technology, including classes, objects, encapsulation and inheritance

Section 30.2—Examining the ATM Requirements Document—discusses a

require-ments document specifying the requirerequire-ments for a system that we’ll design and implement

—the software for a simple automated teller machine (ATM) We investigate the structure

and behavior of object-oriented systems in general We discuss how the UML facilitates

the design process in subsequent Case Study sections by providing several additional types

of diagrams to model our system We discuss the interaction between the ATM system and

its user Specifically, we investigate the scenarios that may occur between the user and the

system itself—called use cases We model these interactions, using UML use case diagrams.

Section 30.3—Identifying the Classes in the ATM Requirements Documents—

begins to design the ATM system We identify its classes by extracting the nouns and noun

phrases from the requirements document We arrange these classes into a UML class

dia-gram that describes the class structure of our system The diadia-gram also describes

relation-ships, known as associations, among the classes.

Section 30.4—Identifying Class Attributes—focuses on the attributes of the classes

discussed in Section 30.3 A class contains both attributes (data) and operations (behaviors).

As we see in later sections, changes in an object’s attributes often affect its behavior To

determine the attributes for the classes in our case study, we extract the adjectives

describing the nouns and noun phrases (which defined our classes) from the requirements

document, then place the attributes in the class diagram we created in Section 30.3

Section 30.5—Identifying Objects’ States and Activities—discusses how an object,

at any given time, occupies a specific condition called a state A state transition occurs when

the object receives a message to change state The UML provides the state machine

dia-gram, which identifies the set of possible states that an object may occupy and models that

object’s state transitions An object also has an activity—the work it performs in its

life-time The UML provides the activity diagram—a flowchart that models an object’s

activity This section uses both diagram types to model behavioral aspects of our ATM

system, such as how it carries out a withdrawal transaction and how it responds when the

user is authenticated

Trang 27

Section 30.6—Identifying Class Operations—identifies the operations, or services,

of our classes We extract from the requirements document the verbs and verb phrases that

specify the operations for each class We then modify the class diagram of Section 30.3 to

include each operation with its associated class As future chapters introduce such topics

as inheritance, we’ll modify our classes and diagrams

Section 30.7—Identifying Collaboration Among Objects—provides a “rough

sketch” of the model for our ATM system In this section, we see how it works We

inves-tigate the behavior of the system by discussing collaborations—messages that objects send

to each other to communicate The class operations that we identified in Section 30.6 turn

out to be the collaborations among the objects in our system We determine the

collabo-rations, then collect them into a communication diagram—the UML diagram for modeling

collaborations This diagram reveals which objects collaborate and when We present a

communication diagram of the collaborations among objects to perform an ATM balance

inquiry We then present the UML sequence diagram for modeling interactions in a system.

This diagram emphasizes the chronological ordering of messages A sequence diagram

models how objects in the system interact to carry out withdrawal and deposit

transac-tions

Section 31.2—Starting to Program the Classes of the ATM System—takes a break

from designing the behavior of our system We begin the implementation process Using

the UML class diagram of Section 30.3 and the attributes and operations discussed in

Section 30.4 and Section 30.6, we show how to implement a class in C# from a design

We do not implement all classes—because we have not completed the design process

Working from our UML diagrams, we create code for the Withdrawal class

Section 31.3—Incorporating Inheritance and Polymorphism into the ATM

System—continues our discussion of object-oriented programming We consider

inheri-tance: classes sharing common characteristics may inherit attributes and operations from

a “base” class In this section, we investigate how our ATM system can benefit from using

inheritance We document our discoveries in a class diagram that models inheritance

rela-tionships—the UML refers to these relationships as generalizations We modify the class

diagram of Section 30.3 by using inheritance to group classes with similar characteristics

This section concludes the design of the model portion of our simulation

Section 31.4—ATM Case Study Implementation—The majority of the case study

involves designing the model (i.e., the data and logic) of the ATM system In this section,

we fully implement that model in C#, working from the UML diagrams we created We

apply the concepts of object-oriented design with the UML and object-oriented

program-ming in C# that you learned in the chapters By the end of this case study, you’ll have

com-pleted the design and implementation of a real-world system and should feel confident

tackling larger systems

Appendix E—UML: Additional Diagram Types—overviews the UML diagram

types not discussed in the OOD/UML Case Study

Dependency Charts

Figures 1–2 illustrate the dependencies among chapters in the book An arrow pointing into

a chapter indicates that it depends on the content of the chapter from which the arrow points.

We’ve commented on some additional dependencies in the diagrams’ footnotes

Trang 28

ptg Dependency Charts xxvii

Fig 1 | Chapter dependency chart for the core-topic chapters

1 Introduction

3 Introduction to C# Applications

5 Control Statements: Part 1

6 Control Statements: Part 2

7 Methods: A Deeper Look

17 Files and Streams 2

20 Searching and Sorting

18 Databases and LINQ 3

19 Web App Development with ASP.NET 4

15 GUI with Windows Forms: Part 2

21 Data Structures

22 Generics

23 Collections

4 Introduction to Classes and Objects

Introduction to Visual C#

Fundamentals and Object-Oriented Programming

Object-Oriented Programming:

A Deeper Look

Strings, Files and

Data Structures

Graphical User Interfaces

Database and Web App Development

9 Introduction to LINQ and the List Collection

1 See Fig 2 for the advanced topics chapters.

2 Requires Sections 14.1–14.5.

3 Requires Sections 14.1–14.6 and 15.8.

4 Requires general GUI and event-handling knowledge (Sections 14.1–14.3).

Dependency Chart

for Core Topics1

Trang 29

Presentation Features

C# 2010 for Programmers, 4/e, contains a rich collection of examples We concentrate on

effective software engineering principles and stress program clarity in the context of

hun-dreds of complete, working programs

Syntax Shading For readability, we syntax shade the code, similar to the way most

inte-grated-development environments and code editors syntax color the code Our

syntax-shading conventions are:

Code Highlighting We place gray rectangles around each program’s key code.

Programming Tips We include programming tips to help you focus on important aspects

of program development These tips and practices represent the best we’ve gleaned from a

combined seven decades of programming and teaching experience

Fig 2 | Chapter dependency chart for the advanced-topic chapters

comments appear like this

keywords appear like this

constants and literal values appear like this

all other code appears in black

9 Introduction to LINQ and

the List Collection

18 Databases and LINQ

19 Web App Development

with ASP.NET

10 Classes and Objects:

A Deeper Look

11 OOP: Inheritance Object-Oriented Programming Object-Oriented Design

Dependency Chart for

Advanced Topics

30 ATM Case Study, Part 1:

Object-Oriented Design with the UML

31 ATM Case Study, Part 2:

Implementing an Object-Oriented Design

24 GUI with Windows Presentation Foundation

25 WPF Graphics and Multimedia WPF GUI and Graphics

Web App Development

1 Chapter 26 depends on the introduction to XML in Chapter 24.

LINQ, Databases and Web

App Development

12 OOP: Polymorphism, Interfaces

and Operator Overloading

Trang 30

ptg Presentation Features xxix

Using Fonts for Emphasis We place the key terms and the index’s page reference for each

defining occurrence in bold text for easier reference On-screen components are

empha-sized in the bold Helvetica font (e.g., the File menu) and C# program text in the Lucida

font (e.g., int x = 5)

Web Access All of the source-code examples for C# 2010 for Programmers, 4/e are available

for download from:

Site registration is quick and easy Download all the examples, then run each program as

you read the corresponding text discussions

Objectives Each chapter begins with a statement of objectives This lets you know what

to expect and gives you an opportunity, after reading the chapter, to determine if you’ve

met the objectives

Quotations The learning objectives are accompanied by quotations Some are humorous;

some are philosophical; others offer interesting insights

Outline The chapter outline helps you approach the material in a top-down fashion, so

you can anticipate what’s to come and set an effective learning pace

Good Programming Practice

The Good Programming Practices call attention to techniques that will help you

pro-duce programs that are clearer, more understandable and more maintainable.

Common Programming Error

Pointing out these Common Programming Errors reduces the likelihood that you’ll

make them.

Error-Prevention Tip

These tips contain suggestions for exposing and removing bugs from your programs; many

of the tips describe aspects of Visual C# that prevent bugs from getting into programs.

Performance Tip

These tips highlight opportunities for making your programs run faster or minimizing the

amount of memory that they occupy.

Portability Tip

The Portability Tips help you write code that will run on a variety of platforms.

Software Engineering Observation

The Software Engineering Observations highlight architectural and design issues that

affect the construction of software systems, especially large-scale systems.

Look-and-Feel Observation

These observations help you design attractive, user-friendly graphical user interfaces that

conform to industry norms.

www.deitel.com/books/csharpfp4/

Trang 31

Illustrations/Figures Abundant charts, tables, line drawings, programs and program

out-put are included We model the flow of control in control statements with UML activity

diagrams UML class diagrams model the fields, constructors and methods of classes We

make extensive use of six major UML diagram types in the OOD/UML ATM case study

Wrap-Up Section Each chapter ends with a brief “wrap-up” section that recaps the

chap-ter content and transitions to the next chapchap-ter

Thousands of Index Entries We’ve included a comprehensive index, which is especially

useful when you use the book as a reference

Software for the Book

We use Microsoft Visual Studio 2010 development tools, including the free Visual C#®

2010 Express Edition, Visual Web Developer 2010 Express Edition and SQL Server 2008

Express Edition The Express Editions provide rich functionality and can be used to build

robust NET applications They are appropriate for professionals who do not have access

to a complete version of Visual Studio 2010

You may use the Express Editions to compile and execute all the example programs

in the book You may also use the full Visual Studio product to build and run the

exam-ples All of the features supported by the Express Editions are also available in the

com-plete Visual Studio 2010 editions

You can download the latest versions of the Express Edition tools from:

When you install the software (discussed in the Before You Begin section that follows this

Preface), you also should install the help documentation and SQL Server Express

Micro-soft provides a dedicated forum for help using the Express Editions at:

Windows 7, Windows Vista and Windows XP

You can use Windows 7, Windows Vista or Windows XP We used Windows 7 while

de-veloping the book We use the Segoe UI font in the graphical user interfaces This font is

accessible to Windows XP users—we tell you how to get it in the Before You Begin

sec-tion Several of our reviewers tested all the programs on Windows XP and reported no

problems If any Windows XP-specific issues arise after the book is published, we’ll post

them at www.deitel.com/books/csharpfp4/ with appropriate instructions Write to us at

deitel@deitel.com if you encounter any problems, and we’ll respond promptly

Other Software Requirements

For Chapters 18, 19, 27 and 28 you’ll need the SQL Server 2008 Express Edition

Chapters 19, 27 and 28 require Visual Web Developer 2010 Express (or a full Visual

Stu-dio 2008 edition) For updates on the software used in this book, subscribe to our free

e-mail newsletter at www.deitel.com/newsletter/subscribe.html, visit the book’s

web-site at www.deitel.com/books/csharpfp4/, and follow us on Twitter (@deitel) and

Facebook (www.deitel.com/deitelfan)

www.microsoft.com/express/

social.msdn.microsoft.com/forums/en-US/Vsexpressinstall/threads/

Trang 32

C# 2010 Fundamentals: Parts I, II and III LiveLessons Video Product xxxi

C# 2010 Fundamentals: Parts I, II and III LiveLessons Video Product

Our C# 2010 Fundamentals: Parts I, II and III LiveLessons Camtasia-based video training

product shows you what you need to know to start building robust, powerful software

with C# 2010 and NET 4 It includes 20+ hours of expert training synchronized to C#

2010 for Programmers, 4/e.

Check out our growing list of LiveLessons video products:

• C# 2010 Fundamentals I, II, and III

• C# 2008 Fundamentals I and II

• Java Fundamentals I and II

• C++ Fundamentals I and II

• iPhone App-Development Fundamentals I and II

• JavaScript Fundamentals I and II

• Visual Basic 2010 Fundamentals I and II

• C Fundamentals I and II

• Android Fundamentals I and II

For additional information about Deitel LiveLessons video products, visit:

Licensing Deitel Book and/or LiveLessons Video Content for Your

Corporate Learning Management Systems

Corporations and organizations may purchase licenses for Deitel’s best-selling book and

LiveLessons video content to be placed on internal learning management systems For

more information, e-mail deitel@deitel.com

The Deitel Online Resource Centers

We provide 100+ online Resource Centers on various topics of interest to our readers—see

the list at www.deitel.com/ResourceCenters.html We’ve found many exceptional

re-sources online, including tutorials, documentation, software downloads, articles, blogs,

pod-casts, videos, code samples, books, e-books and more—most are free Some of the Resource

Centers you might find helpful while studying this book are Visual C#, ASP.NET,

ASP.NET AJAX, LINQ, NET, Silverlight, SQL Server, Web Services, Windows

Commu-nication Foundation, Windows Presentation Foundation, Windows 7, UML, Code Search

Engines and Code Sites, Game Programming and Programming Projects

Acknowledgments

It’s a pleasure to acknowledge the efforts of people whose names do not appear on the

cov-er, but whose hard work, cooperation, friendship and understanding were crucial to the

book’s production Thanks especially to Abbey Deitel and Barbara Deitel

We’re fortunate to have worked on this project with the dedicated publishing

profes-sionals at Prentice Hall/Pearson We appreciate the extraordinary efforts and 15-year

men-torship of our friend and professional colleague Mark L Taub, Editor-in-Chief of Pearson

www.deitel.com/livelessons

Trang 33

Technology Group Thanks to Sandra Schroeder and Chuti Prasertsith for their work on

the cover, and to John Fuller for managing the production of the book

We wish to acknowledge the efforts of our third and fourth edition reviewers

Adhering to tight schedules, they scrutinized the text and the programs and provided

countless suggestions for improving the presentation:

Microsoft Reviewers

Vinay Ahuja (Architect), Dan Crevier, Marcelo Guerra Hahn, Helena Kotas, Eric Lippert,

Kyrylo Osenkov (Visual C#) and Alex Turner (Visual C# Compiler Program Manager)

Other Industry Reviewers

Rizwan Ahmed a.k.a RizwanSharp (C# MVP, Sr Software Engineer, TEO), José

Alarcón-Aguín (ASP.NET MVP, Krasis.com), Mostafa Arafa (C# MVP, Agility

Logis-tics), Bonnie Berent (Microsoft C# MVP), Peter Bromberg (Senior Architect Merrill

Lynch and C# MVP), Adam Calderon (C# MVP, InterKnowlogy), Stochio Goutsev

(In-dependent Consultant, writer and developer and C# MVP), Octavio Hernandez (C#

MVP, Advanced Bionics), Ged Mead (DevCity.Net, Microsoft VB MVP—Visual

Devel-oper) and José Antonio González Seco (Parliament of Andalusia)

Academic Reviewers

Mingsheng Hong (Cornell University), Stan Kurkovsky, Ph.D (Central Connecticut

State University), Markus Lumpe (Swinburne University of Technology), Gavin Osborne

(Saskatchewan Institute of Applied Science and Technology) and Zijiang Yang (Western

Michigan University)

Well, there you have it! Visual C# 2010 is a powerful programming language that will

help you write programs quickly and effectively It scales nicely into the realm of

enter-prise-systems development to help you build business-critical and mission-critical

infor-mation systems As you read the book, we’d appreciate your comments, criticisms,

corrections and suggestions for improvement Please address all correspondence to:

We’ll respond promptly, and we’ll post corrections and clarifications on the book’s website:

We hope you enjoy reading C# 2010 for Programmers, 4/e, as much as we enjoyed writing it!

Paul J Deitel

Dr Harvey M Deitel

About the Authors

Paul J Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate

of MIT, where he studied Information Technology Through Deitel & Associates, Inc.,

he has delivered C#, Visual Basic, Java, C++, C and Internet programming courses to

in-dustry clients, including Cisco, IBM, Sun Microsystems, Dell, Siemens, Lucent

Technol-ogies, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm

Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, SunGard Higher

Education, Stratus, Cambridge Technology Partners, One Wave, Hyperion Software,

deitel@deitel.com

www.deitel.com/books/csharpfp4/

Trang 34

About Deitel & Associates, Inc xxxiii

Adra Systems, Entergy, CableData Systems, Nortel Networks, Puma, iRobot, Invensys

and many more He and his co-author, Dr Harvey M Deitel, are the world’s best-selling

programming-language textbook/professional book authors

Dr Harvey M Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,

Inc., has 49 years of experience in the computer field Dr Deitel earned B.S and M.S

degrees from MIT and a Ph.D from Boston University He has extensive industry and

academic experience, including earning tenure and serving as the Chairman of the

Com-puter Science Department at Boston College before founding Deitel & Associates, Inc.,

with his son, Paul J Deitel He and Paul are the co-authors of dozens of books and

mul-timedia packages and they are writing many more With translations published in

Japa-nese, German, Russian, ChiJapa-nese, Spanish, Koresan, French, Polish, Italian, Portuguese,

Greek, Urdu and Turkish, the Deitels’ texts have earned international recognition Dr

Deitel has delivered hundreds of professional seminars to major corporations, academic

institutions, government organizations and the military

About Deitel & Associates, Inc.

Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally

recognized authoring, corporate training and software development organization

specializ-ing in computer programmspecializ-ing languages, object technology, Android and iPhone app

de-velopment, and Internet and web software technology The company offers instructor-led

training courses delivered at client sites worldwide on major programming languages and

platforms, such as Visual C#®, Java™, C, C++, Visual Basic®, Objective-C and iPhone and

iPad app development, Android app development, XML®, Python®, object technology,

In-ternet and web programming, and a growing list of additional programming and software

development courses The company’s clients include many of the world’s largest companies,

government agencies, branches of the military, and academic institutions

Through its 34-year publishing partnership with Prentice Hall/Pearson, Deitel &

Associates, Inc., publishes leading-edge programming professional books, college

text-books, and LiveLessons DVD- and web-based video courses Deitel & Associates, Inc and

the authors can be reached at:

To learn more about Deitel’s Dive Into ® Series Corporate Training curriculum, visit:

To request a proposal for on-site, instructor-led training at your company or organization,

e-mail deitel@deitel.com

Individuals wishing to purchase Deitel books and LiveLessons DVD training courses

can do so through www.deitel.com Bulk orders by corporations, the government, the

military and academic institutions should be placed directly with Pearson For more

infor-mation, visit www.pearsoned.com/professional/index.htm

deitel@deitel.com

www.deitel.com/training/

Trang 35

This section contains information you should review before using this book and

instruc-tions to ensure that your computer is set up properly for use with this book We’ll post

updates to this Before You Begin section (if any) on the book’s website:

Font and Naming Conventions

We use fonts to distinguish between features, such as menu names, menu items, and other

elements that appear in the program-development environment Our convention is to

em-phasize IDE features in a sans-serif bold Helvetica font (for example, Properties window)

and to emphasize program text in a sans-serif Lucida font (for example, bool x = true)

A Note Regarding Software for the Book

This textbook includes a DVD which contains the Microsoft® Visual Studio® 2010

Ex-press Edition integrated development environments for Visual C# 2010, Visual Basic

2010, Visual C++ 2010, Visual Web Developer 2010 and SQL Server 2008 The latest

versions of these tools are also downloadable from www.microsoft.com/express The

Express Editions are fully functional, and there’s no time limit for using the software We

discuss the setup of this software shortly You do not need Visual Basic or Visual C++ for

use with this book

Hardware and Software Requirements for the Visual Studio 2010 Express Editions

To install and run the Visual Studio 2010 Express Editions, ensure that your system meets

the minimum requirements specified at:

Desktop Theme Settings for Windows 7 Users

If you are using Windows 7, we assume that your theme is set to Windows 7 Follow these

steps to set Windows 7 as your desktop theme:

1 Right click the desktop, then click Personalize

2 Select the Windows 7 theme

Desktop Theme Settings for Windows Vista Users

If you are using Windows Vista, we assume that your theme is set to Windows Vista Follow

these steps to set Windows Vista as your desktop theme:

1 Right click the desktop, then click Personalize

2 Click the Theme item Select Windows Vista from the Theme: drop-down list

3 Click Apply to save the settings

www.deitel.com/books/csharpfp4/

http://www.microsoft.com/express/support/default.aspx

Before You Begin

Trang 36

xxxv

Desktop Theme Settings for Windows XP Users

If you are using Windows XP, the windows you see on the screen will look slightly

differ-ent from the screen captures in the book We assume that your theme is set to Windows

XP Follow these steps to set Windows XP as your desktop theme:

1 Right click the desktop, then click Properties

2 Click the Themes tab Select Windows XP from the Theme: drop-down list

3 Click OK to save the settings

Viewing File Extensions

Several screenshots in C# 2010 for Programmers, 4/e display file names with file-name

ex-tensions (e.g., .txt, .cs or .png) Your system’s settings may need to be adjusted to

dis-play file-name extensions Follow these steps to configure your computer:

1 In the Start menu, select All Programs, then Accessories, then Windows Explorer

2 In Windows 7 and Windows Vista, press Alt to display the menu bar, then select

Folder Options… from Windows Explorer’s Tools menu In Windows XP, simply

select Folder Options… from Windows Explorer’s Tools menu

3 In the dialog that appears, select the View tab

4 In the Advanced settings: pane, uncheck the box to the left of the text Hide

ex-tensions for known file types [Note: If this item is already unchecked, no action

needs to be taken.]

5 Click OK to apply the setting and close the dialog.

Notes to Windows XP Users Regarding the Segoe UI Font Used in Many Applications

To make user interfaces more readable, Microsoft recommends using the Segoe UI font in

Windows 7 and Windows Vista This font is not available by default on Windows XP, but

it is installed with the following software products: Windows Live Messenger, Windows

Live Mail, Microsoft Office 2007 and Microsoft Office 2010 You can download

Win-dows Live Messenger from explore.live.com/windows-live-messenger You can

downloadS Windows Live Mail from explore.live.com/windows-live-mail

You must also enable ClearType on your system; otherwise, the font will not display

correctly ClearType is a technology for smoothing the edges of fonts displayed on the

screen To enable ClearType, perform the following steps:

1 Right click your desktop and select Properties… from the popup menu to view

the Display Properties dialog

2 In the dialog, click the Appearance tab, then click the Effects… button to display

the Effects dialog

3 In the Effects dialog, ensure that the Use the following method to smooth edges of

screen fonts checkbox is checked, then select ClearType from the combobox

be-low the checkbox

4 Click OK to close the Effects dialog Click OK to close the Display Properties

dia-log

Trang 37

Obtaining the Code Examples

The examples for C# 2010 for Programmers, 4/e are available for download at

If you’re not already registered at our website, go to www.deitel.com and click the Register

link below our logo in the upper-left corner of the page Fill in your information There’s

no charge to register, and we do not share your information with anyone We send you

only account-management e-mails unless you register separately for our free e-mail

news-letter at www.deitel.com/newsletter/subscribe.html You must enter a valid email

ad-dress After registering, you’ll receive a confirmation e-mail with your verification code.

Click the link in the confirmation email to go to www.deitel.com and sign in

Next, go to www.deitel.com/books/csharpfp4/ Click the Examples link to

down-load the Examples.zip file to your computer Write down the location where you choose

to save the file on your computer

We assume the examples are located at C:\Examples on your computer Extract the

contents of Examples.zip using a tool such as WinZip (www.winzip.com) or the built-in

capabilities of Windows

Installing the Software

Before you can run the applications in C# 2010 for Programmers, 4/e or build your own

applications, you must install a development environment We used Microsoft’s free

Vi-sual C# 2010 Express Edition in the examples for most chapters and ViVi-sual Web

Devel-oper 2010 Express Edition for Chapters 19 and 27–29 Chapters 18, 27 and 28 also

require SQL Server Express Edition To install the Visual C# 2010 and Visual Web

De-veloper 2010 Express Editions:

1 Insert the DVD that accompanies this book into your computer’s DVD drive to

launch the software installer If the Visual Studio 2010 Express Setup window does

not appear, use Windows Explorer to view the contents of the DVD drive and

double click Setup.hta to launch the installer

2 In the Visual Studio 2010 Express Setup window, click Visual C# 2010 Express to

display the Visual C# 2010 Express Setup window, then click Next >

3 Carefully read the license agreement Click the I have read and accept the license

terms radio button to agree to the terms, then click Next > [Note: If you do not

accept the license agreement, the software will not install and you will not be able

to create or execute Visual C# applications.]

4 Select the MSDN Express Library for Visual Studio 2010, Microsoft SQL Server 2008

Express Edition (x86) and Microsoft Silverlight Runtime options to install Click

Next > [Note: Installing the MSDN documentation is not required but is highly

recommended.]

5 Click Next >, then click Finish > to continue with the installation The installer

will now begin copying the files required by Visual C# 2010 Express Edition and

SQL Server 2008 Express Edition Wait for the installation to complete before

proceeding—the installation process can be quite lengthy and might require you

to reboot your computer When the installation completes, click Exit

www.deitel.com/books/csharpfp4q/

Trang 38

xxxvii

6 In the Visual Studio 2010 Express Setup window, click Visual Web Developer 2010

Express to display the Visual Web Developer 2010 Express Setup window, then

click Next >

7 Carefully read the license agreement Click the I have read and accept the license

terms radio button to agree to the terms, then click Next > [Note: If you do not

accept the license agreement, the software will not install and you will not be able

to create or execute web applications with Visual Web Developer.]

8 Click Install > to continue with the installation The installer will now begin

copying the files required by Visual Web Developer 2010 Express Edition This

portion of the install process should be much faster, since you’ve already installed

most of the supporting software and files required by Visual Web Developer

When the installation completes, click Exit

Miscellaneous Notes

• Some people like to change the workspace layout in the development tools You

can return the tools to their default layouts by selecting Window > Reset Window

Layout

• There are differences between the full Visual Studio 2010 products and the

Express Edition products we use in this book, such as additional menu items One

key difference is that the Database Explorer we refer to in Chapters 18, 27 and 28

is called the Server Explorer in the full Visual Studio 2010 products

• Many of the menu items we use in the book have corresponding icons shown with

each menu item in the menus Many of the icons also appear on one of the

tool-bars at the top of the development environment As you become familiar with

these icons, you can use the toolbars to help speed up your development time

Similarly, many of the menu items have keyboard shortcuts (also shown with each

menu item in the menus) for accessing commands quickly

Trang 39

ptg

Trang 40

1

Introduction

O B J E C T I V E S

In this chapter you’ll learn:

■ The history of the Visual C# programming language

■ Some basics of object technology

■ The importance of XML as a data-representation scheme

■ About Microsoft’s NET initiative, which involves the Internet in developing and using software systems

■ About the NET Framework and the Common Language Runtime

■ To test-drive a Visual C# 2010 drawing application

The chief merit of language

is clearness.

—Galen

Our life is frittered away

with detail Simplify,

simplify.

—Henry David Thoreau

Man is still the most

extraordinary computer of

all.

—John F Kennedy

Ngày đăng: 24/01/2014, 18:38

TỪ KHÓA LIÊN QUAN

w