Tải bản đầy đủ (.pdf) (0 trang)

1295 beginning object oriented programming with c

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (18.62 MB, 0 trang )

www.it-ebooks.info


www.it-ebooks.info

ffirs.indd iv

10/8/2012 8:54:40 AM


BEGINNING
OBJECT-ORIENTED PROGRAMMING WITH C#
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxv

PART I

GETTING STARTED

CHAPTER 1

Introducing C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

CHAPTER 2

Understanding Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19

PART II

UNDERSTANDING C# SYNTAX

CHAPTER 3



Understanding Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

CHAPTER 4

Understanding C# Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81

CHAPTER 5

Understanding Reference Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

CHAPTER 6

Making Decisions in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .147

CHAPTER 7

Statement Repetition Using Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

CHAPTER 8

Understanding Arrays and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . 193

PART III

WRITING YOUR OWN CLASSES

CHAPTER 9

Designing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227


CHAPTER 10

Designing and Writing Custom Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 255

CHAPTER 11

Exception Handling and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

CHAPTER 12

Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327

PART IV STORING DATA
CHAPTER 13

Using Disk Data Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

CHAPTER 14

Using Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425

CHAPTER 15

Using LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Continues

www.it-ebooks.info

ffirs.indd i


10/8/2012 8:54:40 AM


PART V

ADVANCED TOPICS

CHAPTER 16

Inheritance and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475

CHAPTER 17

Printing and Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501

CHAPTER 18

Web Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523

APPENDIX

Answers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577

www.it-ebooks.info

ffirs.indd ii


10/8/2012 8:54:40 AM


BEGINNING

Object-Oriented Programming
with C#

www.it-ebooks.info

ffirs.indd iii

10/8/2012 8:54:40 AM


www.it-ebooks.info

ffirs.indd iv

10/8/2012 8:54:40 AM


BEGINNING

Object-Oriented Programming
with C#
Jack Purdum

www.it-ebooks.info


ffirs.indd v

10/8/2012 8:54:40 AM


Beginning Object-Oriented Programming with C#
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256

www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-33692-2
ISBN: 978-1-118-38794-8 (ebk)
ISBN: 978-1-118-41647-1 (ebk)
ISBN: 978-1-118-54075-6 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 7486008, or online at />Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold
with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services.
If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to

in this work as a citation and/or a potential source of further information does not mean that the author or the publisher
endorses the information the organization or Web site may provide or recommendations it may make. Further, readers
should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was
written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with
standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media
such as a CD or DVD that is not included in the version you purchased, you may download this material at
. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2012948651
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries,
and may not be used without written permission. All other trademarks are the property of their respective owners. John
Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

www.it-ebooks.info

ffirs.indd vi

10/8/2012 8:54:41 AM


To Jane

www.it-ebooks.info

ffirs.indd vii

10/8/2012 8:54:42 AM



www.it-ebooks.info

ffirs.indd viii

10/8/2012 8:54:42 AM


ABOUT THE AUTHOR

DR. JACK PURDUM started his programming career on an IBM 360 mainframe

as a graduate student in the 1960s. In the mid-1970s, he became interested
in software development for microcomputers, and he founded his own software development company (Ecosoft, Inc.) in 1977. The company’s main
product was a statistics package (Microstat) that he wanted to rewrite in a
new language called C. Lacking a suitable C compiler, Dr. Purdum’s company
developed its own MS-DOS-based C compiler and other programming tools.
He has been involved with language instruction ever since. Dr. Purdum has
authored 17 texts and numerous programming articles and has received several teaching awards. He
retired from Purdue University’s College of Technology and is currently involved with on-site training and embedded systems programming.

www.it-ebooks.info

ffirs.indd ix

10/8/2012 8:54:42 AM


www.it-ebooks.info


ffirs.indd x

10/8/2012 8:54:42 AM


CREDITS

Executive Editor

Production Manager

Robert Elliott

Tim Tate

Project Editor

Vice President and Executive Group
Publisher

Tom Dinse

Richard Swadley

Technical Editor
Rod Stephens

Vice President and Executive
Publisher


Production Editor

Neil Edde

Rebecca Anderson

Associate Publisher
Copy Editor

Jim Minatel

Apostrophe Editing Services

Project Coordinator, Cover
Editorial Manager

Katie Crocker

Mary Beth Wakefield

Proofreader
Freelancer Editorial Manager

Sarah Kaikini, Word One

Rosemarie Graham

Indexer
Associate Director of Marketing


Johnna VanHoose

David Mayhew

Cover Designer
Marketing Manager

LeAndra Young

Ashley Zurcher

Cover Image
Business Manager

© Vladislav Lebedinski / iStockPhoto

Amy Knies

www.it-ebooks.info

ffirs.indd xi

10/8/2012 8:54:42 AM


www.it-ebooks.info

ffirs.indd xii

10/8/2012 8:54:42 AM



ACKNOWLEDGMENTS

NO BOOK IS WRITTEN without massive effort by others. Tom Dinse and the editorial staff at Wrox
have all made this a better book.

A large group of people also contributed to this book in a variety of different ways, providing everything from encouragement to ideas for examples. First, thanks to my students who served as guinea
pigs for virtually everything used in this text. Others who contributed include Jerry and Barb Forro,
Bill Gromer, Joe Kack, Katie Mohr, John Purdum, and John Strack. A special vote of appreciation
to Jane Holcer for her unwavering support and encouragement throughout the process of writing
this book.

www.it-ebooks.info

ffirs.indd xiii

10/8/2012 8:54:42 AM


www.it-ebooks.info

ffirs.indd xiv

10/8/2012 8:54:42 AM


CONTENTS

INTRODUCTION


xxv

PART I: GETTING STARTED
CHAPTER 1: INTRODUCING C#

A Short History of Object-Oriented Programming (OOP)
Installing C#
Downloading Visual Studio Professional

A Test Program Using C#

3

4
5
5

8

Creating a Project
The C# Integrated Development Environment
The Major IDE Windows
Using the Source Code Window
Adding a Toolbox Object to a Windows Form
Changing the Text of a Label Object
Running the Program

Summary


9
10
10
12
13
14
16

16

CHAPTER 2: UNDERSTANDING OBJECTS

Understanding Objects

19

20

Everyday Use of Objects
Class Properties
Class Methods
How Many Properties, How Many Methods?
Classes Are Simplifications of Objects
What Do I Do After I’ve Defined a Class?
Instantiating an Object of a Class
I Have an Object…Now What?
Why Hide the Data Inside an Object?

Getting Started with Objects
Developing a Program Plan

Where to Start? The Five Program Steps
The Five Program Steps

Creating a Simple Application Using Objects
Using the Program Steps to Create a Program Plan

20
20
22
23
23
23
26
29
32

32
38
38
38

40
40

www.it-ebooks.info

ftoc.indd xv

10/8/2012 8:54:07 AM



CONTENTS

1: Initialization
2: Input
3: Process
4: Display
5: Termination

40
41
42
43
43

Using C# to Implement Your Program Plan
Critique of the btnDisplayOutput Click Event Code

Summary

43
53

54

PART II: UNDERSTANDING C# SYNTAX
CHAPTER 3: UNDERSTANDING DATA TYPES

Computer Data


59

59

Integer Data Types
Range of Integer Data Types
Understanding Binary Numbers
Signed Integer Values
Which Integer Should You Use?
Variable Naming Rules and Conventions

Floating-Point Data Types
Which Floating-Point Data Type Should You Use?

Monetary Values: The Decimal Data Type
Using IntelliSense to Locate Program Errors
Syntax Rules and Error Messages

The Boolean Data Type
Summary

60
61
61
62
62
63

71
74


74
76
76

77
79

CHAPTER 4: UNDERSTANDING C# STATEMENTS

Basic Building Blocks of a Programming Language
Operands and Operators
Expressions
Statements
Operator Precedence
Overriding the Default Precedence Order

Defining Variables

81

82
82
83
83
84
85

87


Defining a Variable from the Compiler’s Point of View
Step 1: Preliminary Syntax Checking
Step 2: Symbol Table Checking
Step 3: Defining a Variable

Using a Variable in a Program

87
87
87
89

90

xvi

www.it-ebooks.info

ftoc.indd xvi

10/8/2012 8:54:07 AM


CONTENTS

The Bucket Analogy
Types of Program Errors

91
93


Syntax Errors
Semantic Errors
Logic Errors

93
93
94

The Visual Studio Debugger

94

The Debugging Process
Making Repetitious Debugging Easier

Using the Visual Studio Debugger
Setting a Breakpoint
Using a Breakpoint to Examine Variables
Single-Stepping the Program

Defensive Coding

94
95

97
97
98
100


101

Write Your Code So That Someone Else Can Easily Understand It
Use Program Comments
Use Meaningful Variable Names
Avoid Magic Numbers
Use a Consistent Coding Style
Take a Break
Use a Second Set of Eyes

Summary

101
101
103
104
105
105
105

106

CHAPTER 5: UNDERSTANDING REFERENCE DATA TYPES

String Variables

109

110


Defining a String Reference Variable
The Meaning of null
Why Reference Types Are Different from Value Types
Reference Variable Rules
Reference Type Variables Versus Value Type Variables
Why Do Reference Variables Work the Way They Do?
Pass by Value Versus Pass by Reference
A Little Efficiency Gain

Using String Variables

110
111
113
113
115
115
116
116

117

String Concatenation
Shorthand Assignment Operators
String Manipulation
String Length
Letting IntelliSense Show You Properties and Methods
Using an IntelliSense Option
An Important Distinction Between Properties and Methods


117
117
118
118
119
120
120

xvii

www.it-ebooks.info

ftoc.indd xvii

10/8/2012 8:54:07 AM


CONTENTS

Thinking About Object Properties and Methods
Strings and Escape Sequences
Verbatim String Literals

DateTime Reference Objects
DateTime and ToString( ) Conversions
Class Constructors
Invoking the Application
The UpdateTimeInfo( ) Method
Overloaded Methods

Method Signatures
The Refresh Button

Summary

120
131
132

133
133
139
139
140
141
142
143

144

CHAPTER 6: MAKING DECISIONS IN CODE

Relational Operators

147

148

Using Relational Operators—The if Statement
The if-else Statement

Shorthand for Simple if-else: The Ternary Operator
Style Considerations for if and if-else Statements
Nested if Statements

RDC
Logical Operators

148
152
154
155
157

158
160

Using the Logical Operators
Associativity

The switch Statement
Summary

162
163

164
167

CHAPTER 7: STATEMENT REPETITION USING LOOPS


Program Loops

169

170

Good Loops, Bad Loops
The Three Conditions of a Well-Behaved Loop
The for Loop
Increment and Decrement Operators
Sequencing in a for Loop
When to Use a for Loop

Nested for Loops

170
170
171
172
173
179

179

Use the Debugger as a Learning Tool

while Loops

182


182

Why Have More Than One Type of Loop?

do-while Program Loops

184

185

xviii

www.it-ebooks.info

ftoc.indd xviii

10/8/2012 8:54:07 AM


CONTENTS

The continue Statement
Summary

189
190

CHAPTER 8: UNDERSTANDING ARRAYS AND COLLECTIONS

What Is an Array?


193

194

Some Array Details
Array Element Versus Array Index
N – 1 Rule
Casts

The ListView Object
Arrays Are Objects
Multidimensional Arrays
Initializing Arrays

195
195
196
201

201
206
207
211

Variations for Initializing an Array
Which Array Definition/Initialization Syntax Is Best?
Code Like a User
Initializing Multidimensional Arrays
Initializer Lists for String Objects

Ragged Arrays
Defining Ragged Arrays at Runtime

Collections
ArrayList Objects
Summary

212
212
212
213
213
215
215

216
218
221

PART III: WRITING YOUR OWN CLASSES
CHAPTER 9: DESIGNING CLASSES

Class Design

227

228

Scope
Block Scope

Local Scope
Class Scope
Namespace Scope
Visualizing Scope
Why Does C# Support Scope?
Think Before You Write

Designing a Program

230
231
232
232
233
233
235
235

236

The Five Program Steps
Initialization Step
Input Step

236
236
238

xix


www.it-ebooks.info

ftoc.indd xix

10/8/2012 8:54:08 AM


CONTENTS

Process Step
Display Step
Termination Step
Look at the Forest, Not Just the Trees

UML Light

238
238
238
238

239

Access Specifiers
Access Specifiers and Scope
The static Keyword
UML Methods
Design Intent and Access Specifiers for Methods
Class Property and Method Names
Think Like a User


The clsDates Design

239
240
241
242
242
244
245

245

namespace Modifier
Class Organization
static Data Versus Instance Members
Property and Helper Methods
General Methods

247
248
248
249
249

User Interfaces Versus User Interfaces
Summary

252
252


CHAPTER 10: DESIGNING AND WRITING CUSTOM CLASSES

Constructors

255

256

Default Constructors
Nondefault Constructors
Constructor Overloading
Constructor Sloppiness
Fixing the Constructor Problem
Always Call the Default Constructor

Property Methods

256
256
257
257
258
259

259

Property Methods and Getters and Setters
Property Method Rules
How the get Property Methods Work

How Does Visual Studio Know Whether to
Use the get or set Statement Block?

What to Do if an Error Occurs in a Property Method
Method Coupling and Cohesion
Cohesion
Coupling

Class Design for Deck-of-Cards Program
UML Class Diagram for Shuffle Deck Program

260
261
262
263

264
266
266
266

267
268

xx

www.it-ebooks.info

ftoc.indd xx


10/8/2012 8:54:08 AM


CONTENTS

Class Constants and Properties
Class Methods
The clsCardDeck Code
Class Properties, Constructor, and Property Methods
Class General Methods

Designing a Card Game Using clsCardDeck
Design Considerations
What Kind of Architecture?
Sideways Refinement

Summary

268
269
273
275
276

278
279
279
280

291


CHAPTER 11: EXCEPTION HANDLING AND DEBUGGING

Overview

295

296

Bugs
Syntax Errors
Semantic Errors
Logic Errors

296
296
296
297

Input Errors

297

Data Validation
Limit User Input
Check Boxes
Combination Boxes
Date and Time Input

297

298
301
302
304

Exception Handling

306

try-catch Statement Blocks
Anticipating a Specific Exception
Fuzzy Exception Messages
The finally Statement Block

Program Debugging

308
310
312
313

314

The Nature of the Beast
Detection
Isolation
The Visual Studio Debugger
The Locals Window
The Immediate Window
Single-Stepping Through the Program

Backing Up from a Breakpoint
The Debug Toolbar
Finding the Bug
Scaffold Code
Toggling Scaffold Code

314
314
316
316
317
318
318
319
319
320
321
322

xxi

www.it-ebooks.info

ftoc.indd xxi

10/8/2012 8:54:08 AM


CONTENTS


Defensive Coding

322

Summary

323

CHAPTER 12: GENERICS

327

What Are Generics?

327

Recursion
Data Problems

333
333

Introduction to Generics

334

Generics Versus ArrayLists
Boxing and Unboxing

Generic Quicksort


334
335

343

Using Generics with Constraints and Interfaces
Interfaces
Why Use an Interface?
Using an Interface
How Do You Know an Interface Is Implemented for a Data Type?

Summary

347
347
348
349
350

354

PART IV: STORING DATA
CHAPTER 13: USING DISK DATA FILES

Directories

359

360


The DriveInfo Class
Directory Class
DirectoryInfo Class

360
360
361

File Class
FileInfo Class
Types of Files

367
368
369

Textual Versus Binary Data Files

Sequential Versus Random Access Files
Sequential Files
Advantages and Disadvantages of Sequential Files
Random Access Files
Fixed Record Sizes
Advantages and Disadvantages of Random Access Files

370

380
380

380
381
381
383

Serialization and Deserialization

411

To Serialize or Not to Serialize

417

MDI, Menus, and File Dialogs
Summary

418
422

xxii

www.it-ebooks.info

ftoc.indd xxii

10/8/2012 8:54:08 AM


CONTENTS


CHAPTER 14: USING DATABASES

What Is a Database?

425

425

The Structure of a Database
Database Tables, Fields, and Records
Designing Fields for a Database Table
Data Normalization

Creating Your Own Databases
Using SQL Server Management Studio

Using SQL

426
426
427
428

432
432

435

The SELECT Statement
The WHERE Predicate

The ORDER BY Clause
Aggregates

435
436
436
437

A DBMS System

438

Displaying Database Data Without Data Binding
Performing the Query
Edit a Record (UPDATE)

Summary

451
452
454

456

CHAPTER 15: USING LINQ

459

Using LINQ


459

Query Keywords

460

Summary

470

PART V: ADVANCED TOPICS
CHAPTER 16: INHERITANCE AND POLYMORPHISM

What Is Inheritance?

475

476

An Inheritance Example
The Base and Derived Classes
The protected Access Specifier
Advantages of Inherited Relationships
Base Classes Are Not Derived Classes
Abstract Classes

Polymorphism
Extension Methods
Summary


476
478
479
480
491
491

492
495
498

xxiii

www.it-ebooks.info

ftoc.indd xxiii

10/8/2012 8:54:08 AM


×