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

Giáo án - Bài giảng: beginning c# 2008

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 (11.47 MB, 511 trang )

THE EXPERT’S VOICE® IN .NET
N
es
* ' " i -
Beginning
C# 2008
From Novice to Professional
Christian Gross
Apress®
Beginning C# 2008
From Novice to Professional
Christian Gross
Beginning C# 2008: From Novice to Professional
Copyright © 2007 by Christian Gross
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any informadon storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-59059-869-6
ISBN-10 (pbk): 1-59059-869-5
Printed and bound in the United States of America
987654321
Trademarked names may appear in this book. Rather than use a tradem ark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
Lead Editor: Ewan Buckingham
Technical Reviewer: Christian Kenyeres
Editorial Board: Steve Anglin, Ewan Buckingham, Tony Campbell, Gary Cornell, lonathan Gennick,
lason Gilmore, Kevin Goff, Jonathan Hassell, Matthew Moodie, Joseph Ottinger, Jeffrey Pepper,
Ben Renow-Clarke, Dominic Shakeshaft, M att Wade, Tom Welsh
Project Manager: Sofia Marchant


Copy Editor: Marilyn Smith
Associate Production Director: Kari Brooks-Copony
Production Editor: Kelly Winquist
Compositor: Kinetic Publishing Services
Proofreader: Nancy Riddiough
Indexer: Broccoli Information Management
Artist: Kinetic Publishing Services
Cover Designer: Kurt Krames
Manufacturing Director: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny(5>springer-sbm.com, or
visit .
For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley,
CA94705. Phone 510-549-5930, fax510-549-5939, e-mail , or visit .
The information in this book is distributed on an “as is” basis, without warranty. Although every precaution
has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to
any person or entity with respect to any loss or damage caused or alleged to be caused direcdy or indirectiy
by the information contained in this work.
The source code for this book is available to readers at h ttp : //www. apress. com.
Some food for thought when writing software:
“A common mistake that people make when trying to design something
completely foolproof is to underestimate the ingenuity o f complete fools.”
“The major difference between a thing that might go wrong and a thing that
cannot possibly go wrong is that when a thing that cannot possibly go wrong goes
wrong it usually turns out to be impossible to get at or repair.”
—Douglas Adams, Mostly Harmless
Contents at a Glance
About the Author xvii
About the Technical Reviewer

XIX
Introduction XXI
CHAPTER 1 Ready, steady, Go! T
CHAPTER 2 Learning About .NET Number and Value Types

27
CHAPTER 3 Learning About String Manipulations
53
CHAPTER 4 Learning About Data Structures, Decisions, and Loops

77
CHAPTER 5 Learning About c# Exception Handling

ÏÏ5
CHAPTER 6 Learning the Basics of Object-Oriented Programming

137
CHAPTER 7 Learning About Components and Object Hierarchies 165
CHAPTER 8 Learning About Component-Oriented Architecture 199
CHAPTER 9 Learning About Lists, Delegates, and Lambda Expressions 23?
CHAPTER 10 Learning About Persistence 257
CHAPTER 11 Learning About .NET Generics

295
CHAPTER 12 Learning About Application Configuration and
Dynamic Loading 329
CHAPTER 13 Learning About Multithreading 359
CHAPTER 14 Learning About Relational Database Data

389

CHAPTER 15 Learning About LINQ 415
CHAPTER 16 Writing Functional Code in c #
439
CHAPTER 17 Learning About other c# Techniques 455
IN D E X 47?
Contents
About the Author xvii
About the Technical Reviewer xix
Introduction xxi
CHAPTER 1 Ready, Stead y, G o ! T
Downloading and Installing the Tools T
Downloading Visual C# Express
2
Installing Visual C# Express 3
Choosing the Application Type 4
Creating Projects and Solutions 4
Creating the Windows Application 5
Viewing the Source Code 6
Renaming the Solution 6
Saving the Solution 7
Running the Windows Application 7
Making the Windows Application Say Hello 9
Adding Comments to the Application 12
Navigating the User Controls of the Solution 13
Creating the Console Application 16
Adding a Console Application Project to the Solution

16
Making the Console Application Say Hello 16

Setting the Startup Project 17
Running the Console Project
17
Creating the Class Library 17
Adding a Class Library Project to the Solution 17
Moving Functionality 18
Defining References 19
Calling Class Library Functionality 19
Using Variables and Constants 2T
Understanding How the .NET Framework Works

23
The Important Stuff to Remember

25
Some Things for You to Do 26
viii CONTENTS
CHAPTER 2 Learning About .NET Num ber and V alue T y p e s 27
Focusing and Organizing Your Development

27
Organizing the Calculator
28
Focusing the Calculator 30
Implementing the Class Library 32
Writing the AddO Method 34
Writing Code to Test the AddO Method 37
Understanding Problems with Numeric Numbers 42
Understanding Numeric and Value Data Types 44
Understanding Value and Reference Types 44

Understanding the CLR Numeric Types

45
Finishing the Calculator 49
The Important Stuff to Remember

50
Some Things for You to Do 50
CHAPTER 3 Learning About String M an ip u la tio n s 53
Organizing the Translation Application

53
Building the Translator Application
54
Creating the Translator Class 55
Translating Hello 55
Creating the Test Application 56
Answering the Question of Responsibility 57
Investigating the String Type 57
Solving the Extra Whitespace Problem 63
Quoting Strings 67
Character Mapping 67
Dealing with Languages and Cultures 69
Setting Culture and Language in Windows

69
Parsing and Processing Numbers 70
Working with Cultures 72
The Important Stuff to Remember
74

Some Things for You to Do 75
CHAPTER 4 Learning About Data Structures, D ecisions,
and L o o p s 77
Understanding the Depth-First Search Algorithm 77
Implementing User-Defined Types sT
Declaring Structs and Classes sT
Value Type Constraints sT
Organizing the Search Algorithm
87
Writing the Depth-First Search Code 89
Defining and Implementing the Data Structure

89
Defining the Algorithm Test
99
Implementing the Depth-First Search Algorithm ÏÔ3
Running the Depth-First Search Algorithm TTT
The Important Stuff to Remember 112
Some Things for You to Do 113
CHAPTER 5 Learning About C# Exception H an dlin g

115
Understanding Errors, Exceptions, and Exception Handling

TTs
Running the Debugger rfis
Handling Exceptions 117
Catching Exceptions TTs
Implementing Exception Handlers 120
Safeguarding Against Stack Unwinding

124
Filtering Exceptions 128
Writing Exception-Safe Code 130
Writing Defensive Code Ï3Ô
Using Default State 133
Processing Errors That Are Warnings 134
The Important Stuff to Remember 135
Some Things for You to Do 136
CHAPTER 6 Learning the B asics of Object-Oriented
Prog ram m in g 137
Understanding Currency Spreads 138
Organizing the Currency Exchange Application Ï39
Writing Tests for the Currency Exchange Application 139
Getting Started with Structural Code 140
Understanding Base Classes 140
Understanding Inheritance Ï4 Ï
Using C# Properties 143
Understanding Inheritance and Scope Modifiers Ï47
Handling Verification Ï5Ô
Finishing the Base Class 153
Writing the Active Trader and Hotel Trader Currency Converters

154
Implementing ActiveCurrencyTrader 154
Implementing HotelCurrencyTrader 156
CONTENTS ix
CONTENTS
CHAPTER 7
CHAPTER 8
Learning More About Preprocessor Directives, Properties, and Abstract

Methods
More Preprocessor Directive Details

More Property Scope Details
More abstract Keyword Details

The Important Stuff to Remember
Some Things for You to Do
Learning About Components and Object Hierarchies
Understanding Some Basic Tax Concepts
Organizing the Tax Application
Programming Using Ideas

Representing Ideas Using C# Interfaces
Understanding How Inheritance and Components Work

Implementing a Tax Engine
Defining the Interfaces
Implementing a Base Class Tax Engine
Using Default Implementations

Implementing a Base Tax Account

Using the Base Functionality of the Tax Engine to Calculate Taxes

Implementing a Tax Engine and Tax Account
Using the Tax Engine
Learning More About Inheritance and Type Casting

More Inheritance Details


More Type-Casting Details
The Important Stuff to Remember
Some Things for You to Do
Learning About Component-Oriented Architecture

Understanding Kernels
Organizing the Lighting Application
Building the Kernel
Defining the Interfaces
Implementing the Kernel
Defining the Kernel As an Interface Instead of a Class

Building a Complete Application
Defining Some Rooms
Instantiating PublicRoom and PrivateRoom

Learning More About Private Classes and Object Initialization
227
Private Classes 227
Object Initialization with Nested Data Types 227
The Important Stuff to Remember 229
Some Things for You to Do 229
CHAPTER 9 Learning About Lists, D elegates, and
Lam bda Ex p re s s io n s 23?
Managing Collections 23T
Managing a Collection Before C# 2.0

232
Managing a Collection After C# 2.0

236
The Case of the Code That Feels Wrong 237
Using Delegates 240
Using Anonymous Delegates 245
Multicasting with Delegates 246
Using Lambda Expressions 247
Understanding Lambda Expressions 249
Creating the Algorithm 250
Implementing the Algorithm Using Lambda Expressions 250
Learning More About Collection Types 252
Using a Plain-Vanilla List 252
Using a KeyAtelue Pair List 253
Using a Stack 254
Using a Queue 254
The Important Stuff to Remember 255
Some Things for You to Do 255
CHAPTER 10 Learning About P e rsiste n ce 257
Organizing the Lottery-Prediction System

257
Piping Data Using a Console
258
Reading Data from the Console 258
Building a Shell 260
Implementing the TextProcessor Application 270
Piping Binary Data 278
Defining the Interfaces and Implementing the Shell

280
Defining the Type

283
Converting a Text Stream into a Binary Stream 284
Converting a Binary Stream into a Text Stream 285
CONTENTS xi
xii CONTENTS
Tweaking Serialization 287
Performing Custom Serialization 287
Declaring a Data Member as Nonserializable 288
Separating Data Objects from Action Objects 288
Completing Custom Types 289
Implementing GetHashCodeO 289
Implementing EqualsO 292
The Important Stuff to Remember 294
Some Things for You to Do 294
CHAPTER 11 Learning About .NET G e n e ric s
295
Why Use .NET Generics? 295
The Theory of a Server-Side Spreadsheet 298
Architecting a Server-Side Spreadsheet 3ÔT
Designing the Architecture 3ÔÏ
Defining the Server Spreadsheet Interfaces 3Ô2
Implementing the Server Spreadsheet 3ÏT
Using Lambda Expressions in the Spreadsheet

316
Assigning State Without Knowing the Type 320
Overriding the ToStringO Functionality

322
Iterating Data Using Enumerators 323

Using the Spreadsheet 324
Calculating an Average 324
Understanding Why the Calculation Worked

326
The Important Stuff to Remember 327
Some Things for You to Do 328
CHAPTER 12 Learning About A pplicatio n Co nfiguration and
D ynam ic L o a d in g 329
Convention over Configuration
329
Decoupling Using a Configuration Architecture

33Ï
Decoupling Using a Convention Architecture

33Ï
Setting Up the Dynamic Loading Projects

332
Signing an Assembly 334
Setting the Output Path 335
Defining and Processing a Configuration File 336
Creating an XML-Based Configuration File 336
Adding the Dynamic Loading Configuration Items 338
Reading a Configuration File

338
CONTENTS xiii
Dynamically Loading an Assembly

339
Dynamically Instantiating a Type 339
Enhancing the Configuration File 343
Loading a Strongly Named Assembly 348
Relocating a Strongly Named Assembly to the GAC

349
Using Version Numbers
35?
Implementing a Convention-Based Architecture

354
Dynamically Loading Base Class or Interface Types 356
The Important Stuff to Remember
357
Some Things for You to Do 358
CHAPTER 13 Learning About M u ltith re ad in g 359
Understanding Multitasking 359
Preemptive Multitasking 36Ö
Time Slicing 36Ö
Using Threads 363
Creating a New Thread 363
Waiting for the Thread to En d 364
Creating a Thread with State 365
Synchronizing Between Threads 367
How Not to Deadlock Your Code (Mostly) 372
Implementing a Reader/Writer Threaded Architecture

376
Implementing a Producer/Consumer Architecture 38Ö

Using a Hidden Producer/Consumer Implementation
38Ö
Implementing a Generic Producer/Consumer Architecture 382
Using an Asynchronous Approach 384
The Important Stuff to Remember 386
Some Things for You to Do 387
CHAPTER 14 Learning About Relational D atabase D a t a

389
Understanding Relational Databases 389
Relational Database Tables 389
Database Relations 39?
Accessing Relational Databases

394
Designing a Database Using Visual C# Express
395
Configuring the Data Source 396
Adding the Tables 399
Accessing the Database Using AD0.NET 4Ö3
Connecting to a Database 403
Adding Table Data 403
xiv CONTENTS
Selecting Data from a Table 406
Deleting Data from the Database

406
Closing a Database Connection 407
Recapping AD0.NET Usage 407
Using the Dataset Designer 408

Building Relations Between Tables 408
Using the Generated Code
412
The Important Stuff to Remember 414
Some Things for You to Do 414
CHAPTER 15 Learning About LIN Q 415
Finding the Frequency of Winning Numbers 415
Extending the Lottery-Prediction System 416
Implementing a Frequency Solution 419
Learning More LINQ Tricks 425
Selecting and Altering Data 428
Selecting with Anonymous Types 430
Processing Multiple Streams 43?
Sorting the Results 431
Splitting Results into Groups 433
Performing Set Operations 434
Using LINQ in Other Contexts 436
The Important Stuff to Remember 438
Some Things for You to Do 438
CHAPTER 16 W ritin g Functional Code in C# 439
Why Functional Programming? 439
The Essence of Functional Programming 44?
Higher-Order Functions 442
Pure Functions 445
Function Evaluation 450
Recursion 452
The Important Stuff to Remember 453
Some Things for You to Do 453
CONTENTS xv
CHAPTER 17 Learning About Other C# Techniques

455
Operators 455
Using Arithmetic Operators 455
Overloading the Operators 460
The goto Statement 462
.NET Generics Constraints 463
Using the type Constraint 463
Using the new Constraint 465
Using the class Constraint 465
Nullable Types 466
Partial Classes and Methods 468
The Important Stuff to Remember 470
Some Things for You to Do 470
INDEX 47T
About the Author
Many people say that by looking at a person’s dog, you can tell what the
person is like. Well, the picture is of my dog Louys, an English bulldog. And
yes, my English bulldog and I have m any comm on characteristics.
But what about the biography of the author, CHRISTIAN GROSS? It’s
pretty simple: I’m a guy who has spent oodles of time strapped to a chair
debugging and taking apart code. In fact, I really enjoy this business we
call software development. I have loved it ever since I learned how to peek
and poke my first bytes. I have written various books, including Ajax and REST Recipes:
A Problem-Solution Approach, Foundations o f Object-Oriented Programming Using .NET
2.0 Patterns, and A Programmer's Introduction to Windows DNA, all available from Apress.
These days, I enjoy coding and experimenting with .NET, as it is a fascinating environment.
.NET makes me feel like a kid opening a present on Christmas morning. You had an idea what
the gift was, but you were not completely sure. And with .NET, there is no relative giving you
socks or a sweater. It’s excitement all the way!

xvii
About the Technical Reviewer
CHRISTIAN KENYERES, principal architect for Collaborative Consulting, is
a visionary technology professional with more than 15 years of extensive
information technology experience. He has served numerous high-profile
clients as an enterprise architect and boasts a broad range of technical
and business knowledge.
Prior to joining Collaborative, Christian performed consulting for
various companies such as Compaq, EMC, Fidelity Investments, Liberty
Mutual Insurance, and lohn Hancock. He holds B.S. and M.S. degrees in Computer Science
from the University of Massachusetts and Boston University, respectively.
xix
Introduction
T i e first computer programm ing book I read was entitled Programming Windows 3.0 by
Charles Petzold. This was around the time when Microsoft Windows 3.0 (circa 1992) once and
for all showed the industry that Microsoft was a company with a future. Writing code for Wmdows
back then was com plicated by many things: lack of documentation, 16-bit architecture, and
the necessity of buying a compiler separate from the software development kit (SDK). Charles’s
book tied everything together and solved the problem of how to write a program for Windows.
Now the problem s are quite the opposite: we have too m uch documentation, we have
64-bit architectures, and everything including the kitchen sink is thrown into a development
environment. Now we need to figure out what we actually need. We have too many options—
too many ways to solve the same problem. What I am trying to do with this book is the same
thing that Charles did for me when I first started out, and that was to help me figure out what
I needed to write code.
This book is about explaining the C# program ming language in the context of solving
problem s. C# has becom e a sophisticated program m ing language that can achieve m any
goals, but you are left wondering what techniques to use when. This book is here to answer

your questions.
This book is not a reference to all of the features of the C# programming language. I don’t
explain the esoteric C# features. I stick to the C# programming features that you will use day in
and day out. That does not m ean that you will be missing certain Cif programming language
constructs, because I have covered all of the major features.
To get the full benefit of this book, I suggest that you do the exercises at the end of the
chapters. The answers are available on the Apress web site (http: //www. apress. com), and you
can cheat and not do the exercises, but I advise against that.
If you are a beginning programmer who has no clue about C#, and you read this book and
do the exercises, I am almost entirely sure that you will be a solid and knowledgeable C# pro
grammer by the end of the book. If that sounds like a big promise, well, yes it is. The chapter
text is intended to get you acquainted with the C# programming language and how to apply its
features. The exercises are intended to make sure you actually understand the C# programming
language and its features.
The chapter exercises are challenging. They cannot be solved within a few minutes. In fact,
when I did all of the exercises, it took me five working-hour days to do all of them!
If you have any questions, such as, “So what was he trying to get at with that exercise?”
I am available on Skype with the user ID christianhgross. Please don’t just ring me. First chat
using text, and if necessary, we can have a voice conversation. Also, you can send e-mail to me
atchristianhgross@ gmail.com.
Thanks and good luck.
xxi
CHAPTER 1
Ready, Steady, Go!
THiis book is about the C# programming language first and foremost. It is about becoming
a proficient C# programmer. Reading this book from cover to cover will not make you a super-
star, but it will make you a programmer who understands what needs to be done when writing
robust, stable, and maintainable C# applications.
In this chapter, you’ll get started by acquiring the tools you need to develop C# applications

and taking those tools for a test spin. Along the way, you’ll create a couple C# applications.
Downloading and Installing the Tools
Getting started with C# 3.0, you’re probably really excited about writing some code that does
something. It’s like getting your driver’s license and wanting to drive a car without even think
ing about where you want to drive. You just want to drive. The great part of .NET is that you
can start writing some code after you have installed either the .NET software development kit
(.NET SDK) or a Visual Studio integrated development environment (IDE). Downloading and
installing the right environment is critical to taking your first step toward an enjoyable coding
experience.
Note Software version numbers, product descriptions, and technologies can be confusing. Having used
Microsoft technologies for over a decade, I can say that naming a technology or product has never been
Microsoft’s strong point. The technologies have (for the most part) been great, but product classification and
identification have not been so great. Thus, this book covers the C# 3.0 programming language that is used
to v/rite applications for the .NET Framework. With C# 3.0, the .NET 3.0 and 3.5 Frameworks are used. .NET
3.0 gives you all of the essentials, and .NET 3.5 gives you the extras.
1

×