1. Trang chủ
  2. » Giáo án - Bài giảng

beginning c# 3.0 an introduction to object oriented programming

526 822 0

Đ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

Định dạng
Số trang 526
Dung lượng 4,56 MB

Nội dung

Beginning C# 3.0 Jack Purdum Wiley Publishing, Inc. Beginning C# 3.0 Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana ISBN: 978-0-470-26129-3 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 Library of Congress Cataloging-in-Publication Data: Purdum, Jack J. (Jack Jay) Beginning C# 3.0 : an introduction to object oriented programming / Jack Purdum. p. cm. Includes index. ISBN 978-0-470-26129-3 (paper/website) 1. Object-oriented programming (Computer science) 2. C# (Computer program language) I. Title. QA76.64.P88 2008 005.13'3—dc22 2008011056 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 Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions. 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 Website 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 Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites 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 (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, 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. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Contents Acknowledgments xi Introduction xxi Part I: Getting Started 1 Chapter 1: Getting Started 3 A Short History of Object-Oriented Programming (OOP) 4 Installing C# 5 Downloading C# Express 5 Installing C# Express 6 A Test Program Using C# Express 8 Creating a Project 8 The C# Integrated Development Environment 10 Adding an Object to a Windows Form 12 Running the Program 16 Summary 17 Chapter 2: Understanding Objects 19 Understanding Objects 19 Everyday Use of Objects 20 How Many Properties, How Many Methods? 22 What Do I Do After I’ve Defined a Class? 23 Developing a Program Plan 30 Where to Start? 30 Creating a Simple Application Using Objects 32 Using the Program Steps to Create a Program Plan 33 Using C# to Implement Our Program Plan 35 Adding Program References to Your Project 37 Adding a New Item to the Project 38 Setting the Project Properties 40 Adding Objects to the frmMain Object 41 Adding Program Code for the Process Step 44 Contents xiv Constructing the User Interface Object 45 The btnDisplayOutput Click Event Code 46 Critique of the btnDisplayOutput Click Event Code 48 Summary 49 Part II: Understanding C# Syntax 51 Chapter 3: Understanding Data Types 53 Integer Data Types 54 Range of Integer Data Types 54 Which Integer Should You Use? 56 Sequence of Steps to Create a New Project 57 Designing the User Interface 58 Code for the Process Step 58 Variable Naming Rules and Conventions 59 Using the TryParse() Method 60 Floating-Point Data Types 63 Floating-Point Precision 65 Which Floating-Point Data Type Should You Use? 67 Monetary Values: The Decimal Data Type 67 Using Intellisense to Locate Program Errors 68 The Boolean Data Type 70 Summary 72 Exercises 73 Chapter 4: Understanding C# Statements 75 Basic Building Blocks of a Programming Language 76 Operands and Operators 76 Expressions 77 Statements 77 Operator Precedence 78 Overriding the Default Precedence Order 79 Defining Variables 80 Defining a Variable from the Compiler’s Point of View 80 Using a Variable in a Program 83 The Bucket Analogy 85 Types of Program Errors 86 Syntax Errors 86 Semantic Errors 87 Logic Errors 87 Contents xv The Visual Studio Debugger 87 The Debugging Process 87 Making Repetitious Debugging Easier 88 Using the Debugger 88 Defensive Coding 93 Use Program Comments 93 Use Meaningful Variable Names 95 Avoid Magic Numbers 95 Summary 96 Exercises 97 Chapter 5: Understanding Reference Data Types 99 String Variables 100 Defining a String Reference Variable 100 Why Reference Types are Different From Value Types 103 Reference Variable Rules 104 Reference Type Variables Versus Value Type Variables 105 Why Do Reference Variables Work the Way They Do? 105 Pass by Value versus Pass by Reference 106 A Little Efficiency Gain 106 Using String Variables 107 String Manipulation 108 Strings and Escape Sequences 121 Verbatim String Literals 122 DateTime Reference Objects 123 DateTime and ToString() Conversions 123 Summary 134 Exercises 134 Chapter 6: Making Decisions in Code 135 Relational Operators 136 Using Relational Operators — The if Statement 136 The if-else Statement 140 Shorthand for Simple if-else: The Ternary Operator 141 Style Considerations for if and if-else Statements 142 Nested if Statements 144 RDC 145 Cascading if Statements 146 Logical Operators 147 The switch Statement 150 Summary 152 Exercises 152 Contents xvi Chapter 7: Statement Repetition Using Loops 153 Program Loops 153 Good Loops, Bad Loops 154 The for Loop 155 Nested for Loops 162 while Loops 165 Why Have More Than One Type of Loop? 166 do-while Program Loops 167 The continue Statement 171 Summary 172 Exercises 173 Chapter 8: Arrays 175 What is an Array? 175 Some Array Details 177 The Listview Object 183 Arrays are Objects 187 Multidimensional Arrays 189 Initializing Arrays 193 Variations for Initializing an Array 193 Initializing Multidimensional Arrays 195 Initializer Lists for Objects 195 Collections 198 ArrayList Objects 200 Summary 203 Exercises 203 Part III: Writing Your Own Classes 205 Chapter 9: Designing Classes 207 Class Design 208 Adding a Class to a Project 208 Scope 209 Visualizing Scope 213 Why Does C# Support Scope? 214 Designing a Program 215 The Five Program Steps 215 Look at the Forest, Not Just the Trees 218 Contents xvii UML Light 219 Access Specifiers 219 UML Methods 222 Think Like a User 224 The clsDates Design 225 namespace Modifier 227 Class Organization 227 User Interfaces Versus User Interfaces 231 Summary 232 Exercises 232 Chapter 10: Designing and Writing Custom Classes 233 Constructors 233 Default Constructors 234 Non-Default Constructors 234 Constructor Overloading 235 Property Methods 237 Getters and Setters 238 What to Do if an Error Occurs in a Property Method 242 Class Design for Deck-of-Cards Program 244 UML Class Diagram 245 Designing a Card Game Using clsCardDeck 256 Summary 269 Exercises 270 Chapter 11: Exception Handling and Debugging 271 Overview 271 Bugs 272 Program Errors 273 Data Validation 273 Limit User Input 274 Exception Handling 282 try-catch Statement Blocks 283 Program Debugging 288 The Nature of the Beast 289 The Visual Studio Debugger 291 Single-Stepping Through the Program 294 Scaffold Code 296 Defensive Coding 297 Summary 297 Exercises 298 Contents xviii Chapter 12: Generics 299 What are Generics? 299 Recursion 305 Data Problems 305 What are Generics? 306 Generics Versus ArrayLists 306 Using a Generic Class 314 Generic Quicksort 315 Using Generics with Constraints and Interfaces 319 Interfaces 319 Why Use an Interface? 320 Using an Interface 322 Summary 326 Exercises 326 Part IV: Storing Data 327 Chapter 13: Using Disk Data Files 329 Directories 329 The DriveInfo Class 330 Directory Class 330 DirectoryInfo Class 331 File Namespace 337 FileInfo Class 338 Types of Files 339 Textual Versus Binary Data Files 339 Reading the Data 349 Sequential Versus Random Access Files 350 Sequential Files 350 Random Access Files 351 frmMain 356 Navigating the Records 363 Delete a Record 364 clsRandomAccess 364 Serialization and Deserialization 382 To Serialize or Not to Serialize 388 MDI, Menus, and File Dialogs 388 Adding a Menu 389 Adding a File Open Dialog 390 Calling Another Form 392 Contents xix Summary 394 Exercises 394 Chapter 14: Using Databases 395 What is a Database? 395 The Structure of a Database 396 Designing Fields for a Database Table 397 Using Your Own Databases 400 ADO.NET 401 Using SQL 402 The SELECT Statement 402 The WHERE Predicate 403 The ORDER BY Clause 403 Aggregates 404 Creating a New Database 406 Creating a New Table (CREATE TABLE) 408 Adding Records to a Table (INSERT INTO) 413 Edit a Record (UPDATE) 416 Delete a Record (DELETE) 421 Database Queries 421 Binding a DataGridView Object to a Database 423 Using a DataGridView Object Without Data Binding 426 Using LINQ 432 LINQ Query Keywords 432 Namespaces and References for LINQ 435 Summary 441 Exercises 442 Chapter 15: Inheritance and Polymorphism 443 What is Inheritance? 443 An Inheritance Example 444 Base Classes are Not Derived Classes 459 Abstract Classes 459 Polymorphism 460 Sending the Snow-Removal Message 462 Summary 463 Exercises 463 Appendix A: Exercise Solutions 465 Index 495 Introduction Over the past 25 years I ’ ve written 15 books on various programming topics. You might wonder why so many . . . Didn ’ t I get it right the first time? Well, no, I didn ’ t . . . not really. When I wrote my first book over 25 years ago, object - oriented programming (OOP) was obscure at best and unknown to most. Like so many others, I had to go through the OOP learning process before I could appreciate what OOP was all about. I have a feeling that there are a lot of people out there who still feel that way. Each time I teach a programming class, I learn new and better ways to explain things. When I look out across a classroom filled with students and it looks like a still - life painting, it ’ s time to back off, retool, and try a different approach to whatever concept it is I ’ m trying to teach. Every class I ’ ve taught has offered new perspectives on how I teach and how students learn. Changing my examples and the techniques I use to teach programming concepts is one of the reasons I came back to teaching after so many years away . . . I missed the learning experience. A number of the books I wrote were concerned with languages other than C#, but that too provides for an enriching experience for me as an instructor. The strengths and weaknesses of a language can be appreciated only if you ’ ve grappled with some other less - than - perfect languages. The fact that programming languages continue to evolve supports the conclusion that I ’ m not the only one who is still learning. After all this time, the one thing that I have learned with absolute certainty is that whatever I know today will likely be out of date tomorrow. Perhaps the real question you should be asking yourself is, Why should I buy this book instead of someone else ’ s book? Good question . . . and a really short answer won ’ t work. A number of factors come into play, but only one really makes a difference. I have absolutely no doubt that there are programmers out there who can write better code than I can. When I had my own software company, my lead programmer, Tim, could code circles around me. He was an amazing coder. But if you asked Tim to explain something, he fell back toward the end of the line. Indeed, there were times when I thought he fell off the planet. The thing that makes this book different from many others is the fact that I ’ ve tried the techniques, examples, and approach to teaching the various programming concepts on literally thousands of students. I know what works and what doesn ’ t. I ’ ve suffered through many deer - in - the - headlights examples, refined and reworked them to the point where I can actually see some students have an epiphany during the class. So many authors today are, no doubt, brilliant coders, but they haven ’ t had to stumble through the bad examples and teaching methods that simply don ’ t work. What works for you, the writer, rarely works for everyone else. Writing good code does not necessarily equate to writing good books. Some charmed people are capable of both (I think P.J. Plauger, Jon Bentley, Brian Kernighan, and Steve McConnell are examples), but they are rare and far between. Alas, you ’ ve noticed I did not place myself on the list. However, what I may lack in coding skills is (I think) overcome by my teaching experience. Obviously, you ’ ll be the final judge. I think you will find this book informative, clear in its examples, and perhaps even entertaining in its narrative. I hope you ’ ll give it a chance . . . I think you ’ ll enjoy the book. Even more important, however, is that you will come to appreciate all that object - oriented programming and C# can do for you. [...]... well as to many common questions specific to P2P and Wrox books To read the FAQs, click the FAQ link on any P2P page xxv Part I Getting Star ted Chapter 1: Getting Started Chapter 2: Understanding Objects 1 Getting Star ted Welcome to the world of object- oriented programming and C#! The primary goal of this book is to use the C# programming language from Microsoft to teach you object- oriented programming, ... chapter, you will learn: ❑ What an object is ❑ What the term state means with respect to objects ❑ What a class is ❑ What it means to instantiate an object ❑ What properties are ❑ What methods are ❑ How to use some of the objects provided by Visual Studio NET Understanding Objects Suppose you are the personnel manager for a company and you need to hire someone to fill an important position After sifting... Properties Window Toolbar Window Figure 1-7 Back in the Dark Ages of programming, you had to load and run a programming editor to write the program’s source code Next, you had to close the editor and load the language compiler program to check the program’s statements for errors Then you had to load an assembler program to convert the source code to assembly language Finally, you had to load and run a linker... developing C#, not the least of which was that it wanted what are known as type-safe programs that run in a managed environment You’re not ready to appreciate exactly what that means right now, but it will become clear as you learn C# 4 Chapter 1: Getting Started Suffice it to say that C# provides you with a robust object- oriented programming language and an impressive set of tools to tackle almost any programming. .. hurt you to read about them again from a different perspective No shortcuts, remember What This Book Covers This text begins with a non -programming- language introduction to object- oriented programming The goal of that chapter is to present the concept of objects first and then ease into how objects may be viewed in C# Throughout the book I have tried to use common, easily understood examples to introduce... like a diamond rather than some other shape (e.g., a spade) To get an object of the class, you must press the cookie cutter (class template) into the cookie dough (computer memory) in order to get an actual cookie (object) An object is an instance of a class An object, therefore, is something that you can actually use in a program Just as you can’t eat a cookie cutter, you can’t directly use a class... used to describe an object As such, a class is an abstraction or simplification of some object you observe in the real world You can break a class down into two basic components: 1 those properties that describe the object, and 2 those methods, or actions, that you wish to associate with the object Class Properties The class properties are the data that you want to record and associate with an object. .. NET’s C# Express ❑ Installing C# Express ❑ Testing C# Express to ensure it was installed correctly With that in mind, let’s get started A Shor t Histor y of Object - Oriented Programming (OOP) Many people believe that OOP is a product of the 1980s and the work done by Bjarne Stroustrup in moving the C language into the object- oriented world by creating the C++ language Actually, SIMULA 1 (1962) and Simula... good idea of what works and what doesn’t work when it comes to explaining complex topics so that they’re easy to understand Reading each chapter gives you the tools to understand the next chapter Second, I may introduce topics in one chapter and then rely heavily on those topics in a much later chapter In other words, the process used to learn OOP and C# is one that introduces new topics based upon ones... would want that object to be able to talk, wave his or her arms, walk, change clothes, and so forth In short, the class methods determine the behaviors the object is capable of performing Methods are used to describe whatever actions you wish to associate with the object Methods often are used to manipulate the data contained within the object We can depict the phone conversation between Issy and Jack . Use an Interface? 32 0 Using an Interface 32 2 Summary 32 6 Exercises 32 6 Part IV: Storing Data 32 7 Chapter 13: Using Disk Data Files 32 9 Directories 32 9 The DriveInfo Class 33 0 Directory Class 33 0 DirectoryInfo. program language) I. Title. QA76.64.P88 200 8 00 5. 13& apos ;3 dc22 200 801 105 6 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,. 33 0 DirectoryInfo Class 33 1 File Namespace 33 7 FileInfo Class 33 8 Types of Files 33 9 Textual Versus Binary Data Files 33 9 Reading the Data 34 9 Sequential Versus Random Access Files 35 0 Sequential

Ngày đăng: 28/04/2014, 15:33

TỪ KHÓA LIÊN QUAN