331 programming c 3 0, fifth edition

609 136 0
331 programming c 3 0, fifth edition

Đ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

www.it-ebooks.info www.it-ebooks.info FIFTH EDITION Programming C# 3.0 Jesse Liberty and Donald Xie Beijing • Cambridge • Farnham • Kưln • Paris • Sebastopol • Taipei • Tokyo www.it-ebooks.info Programming C# 3.0, Fifth Edition by Jesse Liberty and Donald Xie Copyright © 2008 O’Reilly Media, Inc All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (safari.oreilly.com) For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com Editor: John Osborn Developmental Editor: Brian MacDonald Production Editor: Sumita Mukherji Copyeditor: Audrey Doyle Proofreader: Sumita Mukherji Indexer: Angela Howard Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Jessamyn Read Printing History: July 2001: First Edition February 2002: Second Edition May 2003: Third Edition February 2005: Fourth Edition December 2007: Fifth Edition Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc Programming C# 3.0, the image of an African crowned crane, and related trade dress are trademarks of O’Reilly Media, Inc Java™ is a trademark of Sun Microsystems, Inc Microsoft, MSDN, the NET logo, Visual Basic, Visual C++, Visual Studio, and Windows are registered trademarks of Microsoft Corporation Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein This book uses RepKover™, a durable and flexible lay-flat binding ISBN-10: 0-596-52743-8 ISBN-13: 978-0-596-52743-3 [M] www.it-ebooks.info Table of Contents Preface ix Part I The C# Language C# 3.0 and NET 3.5 The Evolution of C# The C# Language The NET Platform Getting Started: “Hello World” Classes, Objects, and Types Developing “Hello World” Using the Visual Studio 2008 Debugger 14 18 C# Language Fundamentals 21 Types Variables and Constants Whitespace Statements Operators Preprocessor Directives 21 25 33 33 49 59 Classes and Objects 61 Defining Classes Creating Objects Using Static Members Destroying Objects Passing Parameters 62 67 75 79 83 iii www.it-ebooks.info Overloading Methods and Constructors Encapsulating Data with Properties readonly Fields 89 92 96 Inheritance and Polymorphism 98 Specialization and Generalization Inheritance Polymorphism Abstract Classes The Root of All Types: Object Nesting Classes 98 101 102 109 113 115 Operator Overloading 118 Using the operator Keyword Supporting Other NET Languages Creating Useful Operators Logical Pairs The Equality Operator Conversion Operators Putting Operators to Work 118 119 120 120 120 121 121 Structs 127 Defining Structs Creating Structs 128 129 Interfaces 132 Defining and Implementing an Interface Overriding Interface Implementations Explicit Interface Implementation 132 147 151 Arrays, Indexers, and Collections 156 Arrays The foreach Statement Indexers Collection Interfaces Constraints List Queues Stacks Dictionaries iv | Table of Contents 156 162 177 186 190 195 206 208 211 www.it-ebooks.info 10 Strings and Regular Expressions 214 Strings Regular Expressions 215 229 11 Exceptions 241 Throwing and Catching Exceptions Exception Objects 242 252 12 Delegates and Events 256 Events Events and Delegates Anonymous Methods 256 257 271 Part II C# and Data 13 Introducing LINQ 279 Defining and Executing a Query LINQ and C# Anonymous Types Implicitly Typed Local Variables Extension Methods Lambda Expressions in LINQ 280 285 291 291 292 297 14 Working with XML 302 XML Basics (A Quick Review) X Stands for eXtensible Creating XML Documents Searching in XML with XPath Searching Using XPathNavigator XML Serialization 302 304 304 311 322 329 15 Putting LINQ to Work 337 Getting Set Up LINQ to SQL Fundamentals Using Visual Studio LINQ to SQL Designer Retrieving Data Updating Data Using LINQ to SQL Deleting Relational Data LINQ to XML 338 339 344 349 353 358 363 Table of Contents | v www.it-ebooks.info 16 ADO.NET and Relational Databases 368 Relational Databases and SQL The ADO.NET Object Model Getting Started with ADO.NET 368 372 374 Part III Programming with C# 17 Programming ASP.NET Applications 381 Web Forms Fundamentals Creating a Web Form Data Binding 381 385 391 18 Programming WPF Applications 404 WPF in a Very Small Nutshell Building the Application What Have You Learned, Dorothy? 404 406 419 19 Programming Windows Forms Applications 420 Creating the Application 420 Part IV The CLR and the NET Framework 20 Attributes and Reflection 449 Attributes Reflection 449 456 21 Threads and Synchronization 465 Threads Synchronization Race Conditions and Deadlocks 466 474 485 22 Streams 487 Files and Directories Reading and Writing Data Asynchronous I/O Network I/O Web Streams Serialization Isolated Storage vi | Table of Contents 488 499 506 511 527 529 538 www.it-ebooks.info 23 Programming NET and COM 542 Importing ActiveX Controls P/Invoke Pointers 542 551 554 C# Keywords 561 Index 569 Table of Contents | vii www.it-ebooks.info www.it-ebooks.info Preface In 2000, NET revolutionized the way we create both web and Windows applications .NET 2.0 was a dramatic incremental improvement over NET 1.0 This book covers C# 3.0 and NET 3.5, and this time we are looking at an even more significant set of changes C# 3.0 introduces a new generation of changes to a framework that takes an enormous leap forward, revolutionizing the way we program Windows applications, web services, and, to a lesser degree, web applications In 2000, I wrote in the first edition of this book that Microsoft had “bet the company” on NET It was a good bet In 2007, I bet my career on NET by joining Microsoft as senior program manager in the Silverlight Development Division Because one way (my preferred way) to program Silverlight is with C#, I have the opportunity to stay very current with this mature yet rapidly evolving language It is an exciting time for C#; version 3.0 adds a number of tremendously useful features, and the newest edition of Visual Studio makes programming with these features easier than ever It is my goal that you’ll find Programming C# 3.0 to be of great use whether this is your first exposure to NET programming, or you’ve been at it for some time I’ll start with the fundamentals, and introduce new additions to the language not as obscure add-ons, but as the integrated features that they are If you are already a C# 2.0 programmer, feel free to skim through the parts you know The new features are called out by appropriate headings; you won’t inadvertently skip over them But be sure to reread Chapter 12, and all of Parts II and III ix www.it-ebooks.info FileStream class, 499 FileSystemInfo class, 488 filter, of query, 282 Finalize() method, Object, 113 finally block, 242, 250–252 finally keyword, 563 finally statement, 250–252 Find() method List, 195 System.Array, 157 FindAll() method List, 195 System.Array, 157 FindIndex() method List, 195 System.Array, 157 FindLast() method List, 195 System.Array, 157 FindLastIndex() method List, 196 System.Array, 157 first-in, first-out (FIFO) collection (see queues) fixed keyword, 556 float type, 22, 23 folders (see directories) fonts used in this book, xiv for keyword, 563 for loop, 44–47 foreach keyword, 563 foreach loop, 162, 164 ForEach() method List, 196 System.Array, 157 foreign key, relational database, 370 form feed, escape character for, 24 Format() method, String, 218 formatter for serialization, 530 forms (see Web Forms; Windows Forms applications) forward slash (see slash) from clause of query, 282 FullName property DirectoryInfo, 488 FileInfo, 493 functions, C# (see methods) functions, XPath, 321 576 | Index G garbage collection, 23, 79 generalization, 98–101 generic collection interfaces (see collection interfaces) generics, 186 get accessor, 94 get keyword, 563 get() method, for indexers, 180 GetAttributes() method, File, 492 GetCreationTime() method Directory, 488 File, 492 GetDirectories() method Directory, 488, 492 DirectoryInfo, 489 GetEnumerator() method Dictionary, 212 List, 196 Queue, 206 Stack, 208 System.Array, 157 GetFiles() method Directory, 488 DirectoryInfo, 489, 492 GetFileSystemInfos() method, DirectoryInfo, 489 GetHashCode() method, Object, 113 GetLastAccessTime() method, File, 492 GetLastWriteTime() method, File, 493 GetLength() method, System.Array, 157 GetLogicalDrives() method, Directory, 488 GetLongLength() method, System.Array, 157 GetLowerBound() method, System.Array, 157 GetObjectData() method, Dictionary, 212 GetParent() method, Directory, 488 GetProperties() method, XmlAttributeOverrides, 335 GetRange() method, List, 196 GetResponse(), WebRequest, 527 GetResponseStream() method, WebResponse, 527 GetType() method Object, 113 XmlSerializer, 330 GetUpperBound() method, System.Array, 157 www.it-ebooks.info GetValue() method, System.Array, 157 global methods, equivalent to, 75 “goes to” operator (see lambda operator) goto keyword, 564 goto statement, 42 in switch statement, 39, 41 reasons to avoid, 42 graphical user interface (see GUI) greater than operator (>), 54 greater than or equals operator (>=), 54 grids, WPF, 406–408, 414 Griffiths, Ian blog for, 301 Programming WPF, 404 Group class, 234 grouping in query, 290 Groups collection, 234 groups, regular expressions, 234–237 GUI (graphical user interface) programs without (see console applications) H HasAttributes property, XmlElement, 319 hash function for collections, 113 heap, 23 Hejlsberg, Anders (C# creator), “Hello World” example, 7, 14–18 HelpLink property, Exception, 253 HKEY_CURRENT_USER key, 538 Horovitz, Alex (Programming NET 3.5), x, 6, 404 HTML controls, 391 HttpWebRequest class, 527 Hungarian notation, 32 Hurwitz, Dan (Programming ASP.NET), 381, 401 I IAsyncResult interface, 507 ICloneable interface, 73 ICollection interface, 186, 187 IComparable interface, 187, 198–201 IComparer interface, 187, 201–205 identifiers (names), 32 (see also naming conventions) identifiers, preprocessor, 59 IDeserializationCallback interface, 535 IDictionary interface, 187, 212 IDisposable interface, 81 IEnumerable interface, 186, 187–189 IEnumerator interface, 186 #if directive, 60 if else statement, 35–37 IFormatter interface, 530 IList interface, 187 implicit conversions, 24, 121, 124 implicit types, 22 implicitly typed local variables, 291 increment operator (++), 53 increment operators, 52–53 index operator ([]) for arrays, 160 for strings, 222 indexers, 177–181 assignment to, 181–183 based on strings, 183–186 declaring, 177 get() and set() methods for, 180 IndexOf() method List, 196 String, 223 System.Array, 157 information contact information for this book, xvi (see also books; web site resources) inheritance, 98, 101 ini files, 538 Initialize() method, System.Array, 158 initializers, 70–73, 79 inline documentation, inner join, SQL, 372 Insert() method List, 196 String, 223 StringBuilder, 227 InsertRange() method, List, 196 instance members of a class, 75 int keyword, 564 int type, 22, 23 int16 type, 22 int32 type, 22 int64 type, 23 interface keyword, 132 Index | 577 www.it-ebooks.info interfaces, 5, 132 combining, 137–140 compared to abstract classes, 146 defining, 132–134 extending, 136 hiding members of, 154 implementing, 134–136 explicitly, 151–154 multiple interfaces, 136 naming, 133 overriding, 147–151 polymorphism and, potential problems with, 140–146 Interlocked class, 477 internal access modifier, 65 IP address, 512 is-a relationship (see specialization) IsFixedSize property, System.Array, 158 isolated storage, 538–541 IsolatedStorageFileStream object, 538 IsReadOnly property, System.Array, 158 IsSynchronized property, System.Array, 158 Item element for collection classes, 196 Item property, IDictionary, 212 Item() method Dictionary, 212 List, 195 iteration statements, 42–49 while loop, 44 for loop, 44–47 foreach loop, 162, 164 while loop, 43 J jagged arrays, 169–172 Java constant fields, no equivalent for, 132 final class, equivalent for, 112 wrapper classes, equivalent for, 83 join clause of query, 285 Join() method LINQ, 301 String, 218 jump statements break statement, 47 continue statement, 47 goto statement, 42 in switch statement, 39, 41 return statement, 35, 126 (see also unconditional branching statements) 578 | Index K keyboard shortcuts, 17 Keys property, Dictionary, 212 keywords reference, 561–568 L lambda expressions for delegate definitions, 271 in LINQ, 297–301 lambda operator (=>), 272 Language-INtegrated Query (see LINQ) LastAccessTime property DirectoryInfo, 488 FileInfo, 493 last-in, first-out (LIFO) collections (see stacks) LastIndexOf() method List, 196 System.Array, 158 LastWriteTime property DirectoryInfo, 489 FileInfo, 493 late binding, using reflection, 456, 462–464 Learning ASP.NET 2.0 with AJAX (Liberty et al.), 381 Length property FileInfo, 493 String, 218, 222 StringBuilder, 227 System.Array, 158, 160 less than operator (

Ngày đăng: 06/03/2019, 17:01

Từ khóa liên quan

Mục lục

  • Programming C# 3.0, Fifth Edition

    • Table of Contents

    • Preface

      • C# and .NET

      • About This Book

      • What You Need to Use This Book

      • How This Book Is Organized

        • Part I: The C# Language

        • Part II: C# and Data

        • Part III: Programming with C#

        • Part IV: The CLR and the .NET Framework

      • Who This Book Is For

      • Conventions Used in This Book

      • Support

      • We’d Like to Hear from You

      • Using Code Examples

      • Safari® Books Online

      • Acknowledgments

        • From Jesse Liberty

        • From Donald Xie

      • Dedications

        • From Jesse Liberty

        • From Donald Xie

    • Part I The C# Language

      • C# 3.0 and .NET 3.5

        • The Evolution of C#

        • The C# Language

          • A Tiny Bit of History

          • C# Features

        • The .NET Platform

      • Getting Started: “Hello World”

        • Classes, Objects, and Types

          • Methods

          • Comments

          • Console Applications

          • Namespaces

          • The Dot Operator (.)

          • The using Directive

          • Case Sensitivity

          • The static Keyword

        • Developing “Hello World”

          • Editing “Hello World”

          • Compiling and Running “Hello World”

        • Using the Visual Studio 2008 Debugger

      • C# Language Fundamentals

        • Types

          • The Built-In Types

            • Choosing a built-in type

            • Converting built-in types

        • Variables and Constants

          • Definite Assignment

          • Constants

          • Enumerations

          • Strings

          • Identifiers

        • Whitespace

        • Statements

          • Unconditional Branching Statements

          • Conditional Branching Statements

            • if...else statements

            • Nested if statements

            • switch statements: an alternative to nested ifs

            • Switch on string statements

          • Iteration Statements

            • The goto statement

            • The while loop

            • The do...while loop

            • The for loop

            • The foreach statement

            • The continue and break statements

        • Operators

          • The Assignment Operator (=)

          • Mathematical Operators

            • Simple arithmetical operators (+, -, *, /)

            • The modulus operator (%) to return remainders

          • Increment and Decrement Operators

            • Calculate and reassign operators

            • The prefix and postfix operators

          • Relational Operators

          • Use of Logical Operators with Conditionals

          • Operator Precedence

          • The Ternary Operator

        • Preprocessor Directives

          • Defining Identifiers

          • Undefining Identifiers

          • #if, #elif, #else, and #endif

      • Classes and Objects

        • Defining Classes

          • Access Modifiers

          • Method Arguments

        • Creating Objects

          • Constructors

          • Initializers

          • The ICloneable Interface

          • The this Keyword

        • Using Static Members

          • Invoking Static Methods

          • Using Static Constructors

          • Static Classes

          • Using Static Fields

        • Destroying Objects

          • The C# Destructor

          • Destructors Versus Dispose

          • Implementing the Close() Method

          • The using Statement

        • Passing Parameters

          • Passing by Reference

          • Overcoming Definite Assignment with out Parameters

        • Overloading Methods and Constructors

        • Encapsulating Data with Properties

          • The get Accessor

          • The set Accessor

          • Property Access Modifiers

        • readonly Fields

      • Inheritance and Polymorphism

        • Specialization and Generalization

        • Inheritance

          • Implementing Inheritance

        • Polymorphism

          • Creating Polymorphic Types

          • Creating Polymorphic Methods

          • Calling Base Class Constructors

          • Controlling Access

          • Versioning with the new and override Keywords

        • Abstract Classes

          • Limitations of Abstract

          • Sealed Class

        • The Root of All Types: Object

        • Nesting Classes

      • Operator Overloading

        • Using the operator Keyword

        • Supporting Other .NET Languages

        • Creating Useful Operators

        • Logical Pairs

        • The Equality Operator

        • Conversion Operators

        • Putting Operators to Work

      • Structs

        • Defining Structs

        • Creating Structs

          • Structs As Value Types

      • Interfaces

        • Defining and Implementing an Interface

          • Implementing More Than One Interface

          • Extending Interfaces

          • Combining Interfaces

          • Polymorphism with Interfaces

          • Interface Versus Abstract Class

        • Overriding Interface Implementations

        • Explicit Interface Implementation

          • Selectively Exposing Interface Methods

          • Member Hiding

      • Arrays, Indexers, and Collections

        • Arrays

          • Declaring Arrays

          • Understanding Default Values

          • Accessing Array Elements

        • The foreach Statement

          • Initializing Array Elements

          • The params Keyword

          • Multidimensional Arrays

            • Rectangular arrays

            • Jagged arrays

          • Array Bounds

          • Array Conversions

          • Sorting Arrays

        • Indexers

          • Indexers and Assignment

          • Indexing on Other Values

        • Collection Interfaces

          • The IEnumerable<T> Interface

        • Constraints

        • List<T>

          • Implementing IComparable

          • Implementing IComparer

        • Queues

        • Stacks

        • Dictionaries

          • IDictionary<K,V>

      • Strings and Regular Expressions

        • Strings

          • Creating Strings

          • The ToString() Method

          • Manipulating Strings

          • Finding Substrings

          • Splitting Strings

          • Manipulating Dynamic Strings

        • Regular Expressions

          • Using Regular Expressions: Regex

          • Using Regex Match Collections

          • Using Regex Groups

          • Using CaptureCollection

      • Exceptions

        • Throwing and Catching Exceptions

          • The throw Statement

          • The catch Statement

            • Taking corrective action

            • Unwinding the call stack

          • Try/Catch Best Practices

          • The finally Statement

        • Exception Objects

      • Delegates and Events

        • Events

        • Events and Delegates

          • Indirect Invocation

          • Publish and Subscribe/Observer

          • The Publishing Class: Clock

          • Registering to Be Notified

          • Sequence of Events

          • The Danger with Delegates

          • The event Keyword

        • Anonymous Methods

          • Lambda Expressions

          • Callback Methods

    • Part II C# and Data

      • Introducing LINQ

        • Defining and Executing a Query

          • Creating the Query

            • The from clause

            • Filtering

            • Projection (or select)

          • Deferred Query Evaluation

        • LINQ and C#

          • Joining

          • Ordering and the var Keyword

          • Grouping and the group Keyword

        • Anonymous Types

        • Implicitly Typed Local Variables

        • Extension Methods

          • Defining and Using Extension Methods

          • Extension Method Restrictions

        • Lambda Expressions in LINQ

      • Working with XML

        • XML Basics (A Quick Review)

          • Elements

          • XHTML

        • X Stands for eXtensible

        • Creating XML Documents

          • XML Elements

          • XML Attributes

        • Searching in XML with XPath

          • Searching for a Single Node

          • Searching Using Axes

          • Predicates

          • XPath Functions

        • Searching Using XPathNavigator

          • Using XPathNodeIterator

          • Using XPathExpression

        • XML Serialization

          • Customizing XML Serialization Using Attributes

          • Runtime XML Serialization Customization

      • Putting LINQ to Work

        • Getting Set Up

        • LINQ to SQL Fundamentals

        • Using Visual Studio LINQ to SQL Designer

        • Retrieving Data

          • Creating Properties for Each Table

          • A LINQ Query

        • Updating Data Using LINQ to SQL

          • Adding a Customer Record

          • Modifying a Customer Record

        • Deleting Relational Data

        • LINQ to XML

      • ADO.NET and Relational Databases

        • Relational Databases and SQL

          • Tables, Records, and Columns

          • Normalization

          • Declarative Referential Integrity

          • SQL

        • The ADO.NET Object Model

          • DataTables and DataColumns

          • DataRelations

          • Rows

          • Data Adapter

          • DBCommand and DBConnection

          • DataReader

        • Getting Started with ADO.NET

    • Part III Programming with C#

      • Programming ASP.NET Applications

        • Web Forms Fundamentals

          • Web Forms Events

            • Postback versus nonpostback events

            • State

          • Web Forms Life Cycle

        • Creating a Web Form

          • Code-Behind Files

          • Adding Controls

          • Server Controls

        • Data Binding

          • Examining the Code

          • Adding Controls and Events

      • Programming WPF Applications

        • WPF in a Very Small Nutshell

          • Creating a WPF Example

          • The Example Program

        • Building the Application

          • Grids and Stack Panels

          • Sucking on a Fire Hose

            • Our goals

          • Adding Data

            • Instantiating objects declaratively

          • Using the Data in the XAML

          • Defining the Listbox

          • The Complete XAML File

          • Event Handling (Finally!)

        • What Have You Learned, Dorothy?

      • Programming Windows Forms Applications

        • Creating the Application

          • Creating Event Handlers

          • Populating the TreeView Controls

            • TreeNode objects

            • Recursing through the subdirectories

            • Getting the files in the directory

          • Handling TreeView Events

            • Clicking the source TreeView

            • Expanding a directory

            • Clicking the target TreeView

            • Handling the Clear button event

          • Implementing the Copy Button Event

            • Getting the selected files

            • Sorting the list of selected files

          • Handling the Delete Button Event

    • Part IV The CLR and the .NET Framework

      • Attributes and Reflection

        • Attributes

          • Types of Attributes

            • Attribute targets

            • Applying attributes

          • Custom Attributes

            • Declaring an attribute

            • Naming an attribute

            • Constructing an attribute

            • Using an attribute

        • Reflection

          • Viewing Metadata

          • Type Discovery

          • Reflecting on a Type

            • Finding all type members

            • Finding type methods

            • Finding particular type members

          • Late Binding

      • Threads and Synchronization

        • Threads

          • Starting Threads

          • Joining Threads

          • Blocking Threads with Sleep

          • Killing Threads

        • Synchronization

          • Using Interlocked

          • Using Locks

          • Using Monitors

        • Race Conditions and Deadlocks

          • Race Conditions

          • Deadlocks

      • Streams

        • Files and Directories

          • Working with Directories

          • Creating a DirectoryInfo Object

          • Working with Files

          • Modifying Files

        • Reading and Writing Data

          • Binary Files

          • Buffered Streams

          • Working with Text Files

        • Asynchronous I/O

        • Network I/O

          • Creating a Network Streaming Server

          • Creating a Streaming Network Client

          • Handling Multiple Connections

          • Asynchronous Network File Streaming

        • Web Streams

        • Serialization

          • Using a Formatter

          • Working with Serialization

            • Serializing the object

            • Deserializing the object

          • Handling Transient Data

        • Isolated Storage

      • Programming .NET and COM

        • Importing ActiveX Controls

          • Creating an ActiveX Control

          • Importing a Control in .NET

            • Importing a control

            • Manually importing the control

            • Adding the control to the form

        • P/Invoke

        • Pointers

    • C# Keywords

    • Index

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan