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

Tài liệu BEGINNING OBJECT-ORIENTED PROGRAMMING WITH C# doc

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.11 MB, 628 trang )

ffirs.indd ivffirs.indd iv 10/8/2012 8:54:40 AM10/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
ffirs.indd iffirs.indd i 10/8/2012 8:54:40 AM10/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
ffirs.indd iiffirs.indd ii 10/8/2012 8:54:40 AM10/8/2012 8:54:40 AM
BEGINNING
Object-Oriented Programming
with C#
ffirs.indd iiiffirs.indd iii 10/8/2012 8:54:40 AM10/8/2012 8:54:40 AM
ffirs.indd ivffirs.indd iv 10/8/2012 8:54:40 AM10/8/2012 8:54:40 AM
BEGINNING
Object-Oriented Programming
with C#
Jack Purdum
ffirs.indd vffirs.indd v 10/8/2012 8:54:40 AM10/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) 748-
6008, 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 specifi cally disclaim all warranties, including
without limitation warranties of fi tness for a particular purpose. No warranty may be created or extended by sales or pro-
motional 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 pub-
lisher 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 trade-
marks 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.
ffirs.indd viffirs.indd vi 10/8/2012 8:54:41 AM10/8/2012 8:54:41 AM
To Jane
ffirs.indd viiffirs.indd vii 10/8/2012 8:54:42 AM10/8/2012 8:54:42 AM
ffirs.indd viiiffirs.indd viii 10/8/2012 8:54:42 AM10/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 soft-
ware 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 train-
ing and embedded systems programming.
ffirs.indd ixffirs.indd ix 10/8/2012 8:54:42 AM10/8/2012 8:54:42 AM
ffirs.indd xffirs.indd x 10/8/2012 8:54:42 AM10/8/2012 8:54:42 AM
CREDITS
Executive Editor
Robert Elliott
Project Editor
Tom Dinse
Technical Editor
Rod Stephens
Production Editor
Rebecca Anderson
Copy Editor
Apostrophe Editing Services
Editorial Manager
Mary Beth Wakefi eld
Freelancer Editorial Manager
Rosemarie Graham
Associate Director of Marketing
David Mayhew
Marketing Manager

Ashley Zurcher
Business Manager
Amy Knies
Production Manager
Tim Tate
Vice President and Executive Group
Publisher
Richard Swadley
Vice President and Executive
Publisher
Neil Edde
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Katie Crocker
Proofreader
Sarah Kaikini, Word One
Indexer
Johnna VanHoose
Cover Designer
LeAndra Young
Cover Image
© Vladislav Lebedinski / iStockPhoto
ffirs.indd xiffirs.indd xi 10/8/2012 8:54:42 AM10/8/2012 8:54:42 AM
ffirs.indd xiiffirs.indd xii 10/8/2012 8:54:42 AM10/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 every-
thing 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.
ffirs.indd xiiiffirs.indd xiii 10/8/2012 8:54:42 AM10/8/2012 8:54:42 AM
ffirs.indd xivffirs.indd xiv 10/8/2012 8:54:42 AM10/8/2012 8:54:42 AM
CONTENTS
INTRODUCTION xxv
PART I: GETTING STARTED
CHAPTER 1: INTRODUCING C# 3
A Short History of Object-Oriented Programming (OOP) 4
Installing C# 5
Downloading Visual Studio Professional 5
A Test Program Using C# 8
Creating a Project 9
The C# Integrated Development Environment 10
The Major IDE Windows 10
Using the Source Code Window 12
Adding a Toolbox Object to a Windows Form 13
Changing the Text of a Label Object 14
Running the Program 16
Summary 16
CHAPTER 2: UNDERSTANDING OBJECTS 19
Understanding Objects 20
Everyday Use of Objects 20
Class Properties 20
Class Methods 22
How Many Properties, How Many Methods? 23
Classes Are Simplifi cations of Objects 23
What Do I Do After I’ve Defi ned a Class? 23

Instantiating an Object of a Class 26
I Have an Object…Now What? 29
Why Hide the Data Inside an Object? 32
Getting Started with Objects 32
Developing a Program Plan 38
Where to Start? The Five Program Steps 38
The Five Program Steps 38
Creating a Simple Application Using Objects 40
Using the Program Steps to Create a Program Plan 40
ftoc.indd xvftoc.indd xv 10/8/2012 8:54:07 AM10/8/2012 8:54:07 AM
xvi
CONTENTS
1: Initialization 40
2: Input 41
3: Process 42
4: Display 43
5: Termination 43
Using C# to Implement Your Program Plan 43
Critique of the btnDisplayOutput Click Event Code 53
Summary 54
PART II: UNDERSTANDING C# SYNTAX
CHAPTER 3: UNDERSTANDING DATA TYPES 59
Computer Data 59
Integer Data Types 60
Range of Integer Data Types 61
Understanding Binary Numbers 61
Signed Integer Values 62
Which Integer Should You Use? 62
Variable Naming Rules and Conventions 63
Floating-Point Data Types 71

Which Floating-Point Data Type Should You Use? 74
Monetary Values: The Decimal Data Type 74
Using IntelliSense to Locate Program Errors 76
Syntax Rules and Error Messages 76
The Boolean Data Type 77
Summary 79
CHAPTER 4: UNDERSTANDING C# STATEMENTS 81
Basic Building Blocks of a Programming Language 82
Operands and Operators 82
Expressions 83
Statements 83
Operator Precedence 84
Overriding the Default Precedence Order 85
Defi ning Variables 87
Defi ning a Variable from the Compiler’s Point of View 87
Step 1: Preliminary Syntax Checking 87
Step 2: Symbol Table Checking 87
Step 3: Defi ning a Variable 89
Using a Variable in a Program 90
ftoc.indd xviftoc.indd xvi 10/8/2012 8:54:07 AM10/8/2012 8:54:07 AM
xvii
CONTENTS
The Bucket Analogy 91
Types of Program Errors 93
Syntax Errors 93
Semantic Errors 93
Logic Errors 94
The Visual Studio Debugger 94
The Debugging Process 94
Making Repetitious Debugging Easier 95

Using the Visual Studio Debugger 97
Setting a Breakpoint 97
Using a Breakpoint to Examine Variables 98
Single-Stepping the Program 100
Defensive Coding 101
Write Your Code So That Someone Else Can Easily Understand It 101
Use Program Comments 101
Use Meaningful Variable Names 103
Avoid Magic Numbers 104
Use a Consistent Coding Style 105
Take a Break 105
Use a Second Set of Eyes 105
Summary 106
CHAPTER 5: UNDERSTANDING REFERENCE DATA TYPES 109
String Variables 110
Defi ning a String Reference Variable 110
The Meaning of null 111
Why Reference Types Are Di erent from Value Types 113
Reference Variable Rules 113
Reference Type Variables Versus Value Type Variables 115
Why Do Reference Variables Work the Way They Do? 115
Pass by Value Versus Pass by Reference 116
A Little E ciency Gain 116
Using String Variables 117
String Concatenation 117
Shorthand Assignment Operators 117
String Manipulation 118
String Length 118
Letting IntelliSense Show You Properties and Methods 119
Using an IntelliSense Option 120

An Important Distinction Between Properties and Methods 120
ftoc.indd xviiftoc.indd xvii 10/8/2012 8:54:07 AM10/8/2012 8:54:07 AM
xviii
CONTENTS
Thinking About Object Properties and Methods 120
Strings and Escape Sequences 131
Verbatim String Literals 132
DateTime Reference Objects 133
DateTime and ToString( ) Conversions 133
Class Constructors 139
Invoking the Application 139
The UpdateTimeInfo( ) Method 140
Overloaded Methods 141
Method Signatures 142
The Refresh Button 143
Summary 144
CHAPTER 6: MAKING DECISIONS IN CODE 147
Relational Operators 148
Using Relational Operators—The if Statement 148
The if-else Statement 152
Shorthand for Simple if-else: The Ternary Operator 154
Style Considerations for if and if-else Statements 155
Nested if Statements 157
RDC 158
Logical Operators 160
Using the Logical Operators 162
Associativity 163
The switch Statement 164
Summary 167
CHAPTER 7: STATEMENT REPETITION USING LOOPS 169

Program Loops 170
Good Loops, Bad Loops 170
The Three Conditions of a Well-Behaved Loop 170
The for Loop 171
Increment and Decrement Operators 172
Sequencing in a for Loop 173
When to Use a for Loop 179
Nested for Loops 179
Use the Debugger as a Learning Tool 182
while Loops 182
Why Have More Than One Type of Loop? 184
do-while Program Loops 185
ftoc.indd xviiiftoc.indd xviii 10/8/2012 8:54:07 AM10/8/2012 8:54:07 AM
xix
CONTENTS
The continue Statement 189
Summary 190
CHAPTER 8: UNDERSTANDING ARRAYS AND COLLECTIONS 193
What Is an Array? 194
Some Array Details 195
Array Element Versus Array Index 195
N – 1 Rule 196
Casts 201
The ListView Object 201
Arrays Are Objects 206
Multidimensional Arrays 207
Initializing Arrays 211
Variations for Initializing an Array 212
Which Array Defi nition/Initialization Syntax Is Best? 212
Code Like a User 212

Initializing Multidimensional Arrays 213
Initializer Lists for String Objects 213
Ragged Arrays 215
Defi ning Ragged Arrays at Runtime 215
Collections 216
ArrayList Objects 218
Summary 221
PART III: WRITING YOUR OWN CLASSES
CHAPTER 9: DESIGNING CLASSES 227
Class Design 228
Scope 230
Block Scope 231
Local Scope 232
Class Scope 232
Namespace Scope 233
Visualizing Scope 233
Why Does C# Support Scope? 235
Think Before You Write 235
Designing a Program 236
The Five Program Steps 236
Initialization Step 236
Input Step 238
ftoc.indd xixftoc.indd xix 10/8/2012 8:54:08 AM10/8/2012 8:54:08 AM
xx
CONTENTS
Process Step 238
Display Step 238
Termination Step 238
Look at the Forest, Not Just the Trees 238
UML Light 239

Access Specifi ers 239
Access Specifi ers and Scope 240
The static Keyword 241
UML Methods 242
Design Intent and Access Specifi ers for Methods 242
Class Property and Method Names 244
Think Like a User 245
The clsDates Design 245
namespace Modifi er 247
Class Organization 248
static Data Versus Instance Members 248
Property and Helper Methods 249
General Methods 249
User Interfaces Versus User Interfaces 252
Summary 252
CHAPTER 10: DESIGNING AND WRITING CUSTOM CLASSES 255
Constructors 256
Default Constructors 256
Nondefault Constructors 256
Constructor Overloading 257
Constructor Sloppiness 257
Fixing the Constructor Problem 258
Always Call the Default Constructor 259
Property Methods 259
Property Methods and Getters and Setters 260
Property Method Rules 261
How the get Property Methods Work 262
How Does Visual Studio Know Whether to
Use the get or set Statement Block? 263
What to Do if an Error Occurs in a Property Method 264

Method Coupling and Cohesion 266
Cohesion 266
Coupling 266
Class Design for Deck-of-Cards Program 267
UML Class Diagram for Shu e Deck Program 268
ftoc.indd xxftoc.indd xx 10/8/2012 8:54:08 AM10/8/2012 8:54:08 AM
xxi
CONTENTS
Class Constants and Properties 268
Class Methods 269
The clsCardDeck Code 273
Class Properties, Constructor, and Property Methods 275
Class General Methods 276
Designing a Card Game Using clsCardDeck 278
Design Considerations 279
What Kind of Architecture? 279
Sideways Refi nement 280
Summary 291
CHAPTER 11: EXCEPTION HANDLING AND DEBUGGING 295
Overview 296
Bugs 296
Syntax Errors 296
Semantic Errors 296
Logic Errors 297
Input Errors 297
Data Validation 297
Limit User Input 298
Check Boxes 301
Combination Boxes 302
Date and Time Input 304

Exception Handling 306
try-catch Statement Blocks 308
Anticipating a Specifi c Exception 310
Fuzzy Exception Messages 312
The fi nally Statement Block 313
Program Debugging 314
The Nature of the Beast 314
Detection 314
Isolation 316
The Visual Studio Debugger 316
The Locals Window 317
The Immediate Window 318
Single-Stepping Through the Program 318
Backing Up from a Breakpoint 319
The Debug Toolbar 319
Finding the Bug 320
Sca old Code 321
Toggling Sca old Code 322
ftoc.indd xxiftoc.indd xxi 10/8/2012 8:54:08 AM10/8/2012 8:54:08 AM
xxii
CONTENTS
Defensive Coding 322
Summary 323
CHAPTER 12: GENERICS 327
What Are Generics? 327
Recursion 333
Data Problems 333
Introduction to Generics 334
Generics Versus ArrayLists 334
Boxing and Unboxing 335

Generic Quicksort 343
Using Generics with Constraints and Interfaces 347
Interfaces 347
Why Use an Interface? 348
Using an Interface 349
How Do You Know an Interface Is Implemented for a Data Type? 350
Summary 354
PART IV: STORING DATA
CHAPTER 13: USING DISK DATA FILES 359
Directories 360
The DriveInfo Class 360
Directory Class 360
DirectoryInfo Class 361
File Class 367
FileInfo Class 368
Types of Files 369
Textual Versus Binary Data Files 370
Sequential Versus Random Access Files 380
Sequential Files 380
Advantages and Disadvantages of Sequential Files 380
Random Access Files 381
Fixed Record Sizes 381
Advantages and Disadvantages of Random Access Files 383
Serialization and Deserialization 411
To Serialize or Not to Serialize 417
MDI, Menus, and File Dialogs 418
Summary 422
ftoc.indd xxiiftoc.indd xxii 10/8/2012 8:54:08 AM10/8/2012 8:54:08 AM
xxiii
CONTENTS

CHAPTER 14: USING DATABASES 425
What Is a Database? 425
The Structure of a Database 426
Database Tables, Fields, and Records 426
Designing Fields for a Database Table 427
Data Normalization 428
Creating Your Own Databases 432
Using SQL Server Management Studio 432
Using SQL 435
The SELECT Statement 435
The WHERE Predicate 436
The ORDER BY Clause 436
Aggregates 437
A DBMS System 438
Displaying Database Data Without Data Binding 451
Performing the Query 452
Edit a Record (UPDATE) 454
Summary 456
CHAPTER 15: USING LINQ 459
Using LINQ 459
Query Keywords 460
Summary 470
PART V: ADVANCED TOPICS
CHAPTER 16: INHERITANCE AND POLYMORPHISM 475
What Is Inheritance? 476
An Inheritance Example 476
The Base and Derived Classes 478
The protected Access Specifi er 479
Advantages of Inherited Relationships 480
Base Classes Are Not Derived Classes 491

Abstract Classes 491
Polymorphism 492
Extension Methods 495
Summary 498
ftoc.indd xxiiiftoc.indd xxiii 10/8/2012 8:54:08 AM10/8/2012 8:54:08 AM

×