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

C# 2008 pot

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 (19.46 MB, 844 trang )

Updates, source code, and Wrox technical support at www.wrox.com
Professional
Visual Studio
®

Extensibility
Keyvan Nayyeri
Wrox Programmer to Programmer
TM
Enhance Your Knowledge
Advance Your Career
Professional Visual Studio 2008
978-0-470-22988-0
In these pages you’ll learn to harness every key feature of Visual Studio.
The opening section will familiarize you with the IDE structure and layout,
various options and settings, and other core aspects of Visual Studio
2008. Then you will examine each of the nine major categories composing
the functions of Visual Studio 2008. Every chapter is cross-referenced,
so you can achieve a complete understanding of each feature and how
all the elements work together to produce an effective programming
environment.
Professional Visual Studio Extensibility
978-0-470-23084-8
Whether you want to integrate optimized builds, enhanced programming
tools, or other rapid application development features, this unique
resource shows you how to develop customized addins using C#.
C# 2008 Programmer’s Reference
978-0-470-28581-7
C# 2008 Programmers Reference provides a concise and thorough
reference on all aspects of the language. Each chapter contains detailed


code samples that provide a quick and easy way to understand the key
concepts covered.
Professional C# 2008
978-0-470-19137-8
Updated for .NET 3.5 and Visual Studio® 2008, this book is the ultimate
guide to C# 2008 and its environment. The team of superlative authors
explain why the C# language cannot be viewed in isolation, but rather,
must be considered in parallel with the .NET Framework.
Beginning Microsoft Visual C# 2008
978-0-470-19135-4
Aimed at novice programmers who wish to learn programming with C# and
the .NET framework, this book starts with absolute programming basics,
then moves into Web and Windows programming, data access (databases
and XML), and more advanced technologies.
Beginning C# 3.0:
An Introduction to Object Oriented Programming
978-0-470-26129-3
This book is written for those readers with no prior programming
experience who want a thorough, yet easy to understand, introduction to
C# and Object Oriented Programming.
C# 2008
Programmer’s Reference
Get more out of
WROX.com
Programmer to Programmer

Interact
Take an active role online by participating in
our P2P forums
Wrox Online Library

Hundreds of our books are available online
through Books24x7.com
Wrox Blox
Download short informational pieces and
code to keep you up to date and out of
trouble!
Chapters on Demand
Purchase individual book chapters in pdf
format
Join the Community
Sign up for our free monthly newsletter at
newsletter.wrox.com
Browse
Ready for more Wrox? We have books and
e-books available on .NET, SQL Server, Java,
XML, Visual Basic, C#/ C++, and much more!
Contact Us.
We always like to get feedback from our readers. Have a book idea?
Need community support? Let us know by e-mailing
spine=1.68"
C# 2008 Programmer’s Reference
Introduction xxv
Part I: C# Fundamentals
Chapter 1: The .NET Framework 3
Chapter 2: Getting Started with Visual Studio 2008 11
Chapter 3: C# Language Foundations 61
Chapter 4: Classes and Objects 125
Chapter 5: Interfaces 171
Chapter 6: Inheritance 183
Chapter 7: Delegates and Events 213

Chapter 8: Strings and Regular Expressions 241
Chapter 9: Generics 265
Chapter 10: Threading 293
Chapter 11: Files and Streams 321
Chapter 12: Exception Handling 377
Chapter 13: Arrays and Collections 397
Chapter 14: Language Integrated Query (LINQ) 425
Chapter 15: Assemblies and Versioning 467
Part II: Application Development Using C#
Chapter 16: Developing Windows Applications 503
Chapter 17: Developing ASP.NET Web Applications 545
Chapter 18: Developing Windows Mobile Applications 573
Chapter 19: Developing Silverlight Applications 617
Chapter 20: Windows Communication Foundation 695
Part III: Appendixes
Appendix A: C# Keywords 749
Appendix B: Examining the .Net Class Libraries Using the Object Browser 757
Appendix C: Generating Documentation for Your C# Applications 765
Index 781
ffirs.indd iffirs.indd i 10/1/08 12:13:05 PM10/1/08 12:13:05 PM
ffirs.indd iiffirs.indd ii 10/1/08 12:13:06 PM10/1/08 12:13:06 PM
C# 2008
Programmer’s Reference
ffirs.indd iiiffirs.indd iii 10/1/08 12:13:06 PM10/1/08 12:13:06 PM
ffirs.indd ivffirs.indd iv 10/1/08 12:13:06 PM10/1/08 12:13:06 PM
C# 2008
Programmer’s Reference
Wei-Meng Lee
Wiley Publishing, Inc.
ffirs.indd vffirs.indd v 10/1/08 12:13:06 PM10/1/08 12:13:06 PM

C# 2008 Programmer’s Reference
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-28581-7
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data
Lee, Wei-Meng.
C# 2008 programmer’s reference / Wei-Meng Lee.
p. cm.
Includes index.
ISBN 978-0-470-28581-7 (paper/website)
1. C# (Computer program language) I. Title.
QA76.73.C154L33 2009
005.13'3—dc22
2009036345
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
/>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.
ffirs.indd viffirs.indd vi 10/1/08 12:13:06 PM10/1/08 12:13:06 PM
To my family and wife, Shihua, for their support and love.
ffirs.indd viiffirs.indd vii 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
ffirs.indd viiiffirs.indd viii 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
About the Author
Wei - Meng Lee, Microsoft MVP, is a technologist and founder of Developer Learning Solutions
(
www.learn2develop.net ), a technology company specializing in hands - on training in the latest
Microsoft and Apple technologies.
Wei - Meng writes extensively for online publications such as DevX.com and the O’Reilly Network and
magazines such as CoDe Magazine and asp.netPRO magazine on topics ranging from .NET to Mac OS X.

He is also the author of Professional Windows Vista Gadgets Programming (Wrox) and Practical .NET 2.0
Networking Projects (Apress).
You can contact Wei - Meng at
About the Technical Editor
Andrew Moore is a graduate of Purdue University – Calumet in Hammond, Indiana, and has been
developing software since 1998 for radar systems, air traffic management, discrete - event simulation, and
business communications applications using C, C++, C#, and Java on the Windows, UNIX, and Linux
platforms. Andrew is the author of Wrox Blox articles titled “ Create Amazing Custom User Interfaces
with WPF, C#, and XAML in .NET 3.0, ” , “ .NET 3.5 CD Audio Player, ” and “ Power Programming with
ReSharper. ” He is currently a senior software engineer at Interactive Intelligence, Inc. in Indianapolis
developing Microsoft - based applications for business communications. Andrew lives in Indiana with his
wife, Barbara, and children, Sophia and Andrew.
ffirs.indd ixffirs.indd ix 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
ffirs.indd xffirs.indd x 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
Credits
Acquisitions Editor
Katie Mohr
Development Editor
Maryann Steinhart
Technical Editor
Andrew Moore
Production Editor
Christine O ’ Connor
Copy Editor
Foxxe Editorial Services
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher

Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Project Coordinator, Cover
Lynsey Stanford
Proofreader
C.M. Jones
Indexer
Robert Swanson
ffirs.indd xiffirs.indd xi 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
ffirs.indd xiiffirs.indd xii 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
Acknowledgments
Writing a book is like running a long race — you need stamina, training, and perseverance. But these are
not the most important factors that ensure you reach the finishing line. The most important factor is the
motivation that keeps you going, on and on, even though you may be physically exhausted and don ’ t
think you can move any farther. While this is not the first book I have written, I am always very excited
when embarking on a new book project. After the excitement comes a lot of hard work — coping with
missed deadlines, changing work schedules, writer ’ s block, and so forth.
For this book, I am extremely lucky to work with two very important people — my acquisitions editor,
Katie Mohr, and development editor, Maryann Steinhart. Both Katie and Maryann have been very
patient with me when the going gets tough. Katie has always egged me on, and offered many
suggestions to scope the book to what it is today. Maryann has been the studious timekeeper, with a
gentle but firm voice telling me to press forward when I missed the deadline. Maryann has also
painstakingly read and reread every sentence I wrote, and I am always surprised with her attention to
detail which has definitely made this book a better one. With heart - felt sincerity, I want to say a big
thank you to both of them!
I would also like to thank the technical editor, Andrew Moore, for giving me many suggestions for
improving the book. Writing this book has made me learn a lot of things I never knew. Thanks, Andrew!
Last but not least, I want to take this opportunity to thank my parents and my wife, Shihua, for their
understanding and support when I have had to take time away to work on this book. Thanks!

ffirs.indd xiiiffirs.indd xiii 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
ffirs.indd xivffirs.indd xiv 10/1/08 12:13:07 PM10/1/08 12:13:07 PM
Contents
Introduction XXV
Part I: C# Fundamentals 1
Chapter 1: The .NET Framework 3
What’s the .NET Framework? 3
Common Language Runtime 3
.NET Framework Class Library 4
Assemblies and the Microsoft Intermediate Language (MSIL) 6
Versions of the .NET Framework and Visual Studio 8
Summary 9
Chapter 2: Getting Started with Visual Studio 2008 11
Visual Studio 2008 Overview 11
Choosing the Development Settings 12
Resetting the Development Settings 13
Creating a New Project 14
Components of the IDE 17
Code and Text Editor 34
Code Snippets 35
IntelliSense 37
Refactoring Support 39
Debugging 49
Setting Breakpoints 49
Stepping through the Code 51
Watching 52
Autos and Immediate Windows 53
Unit Testing 53
Creating the Test 54
Running the Test 57

Testing with Floating Point Numbers 58
Adding Additional Test Methods 59
Summary 59
ftoc.indd xvftoc.indd xv 10/1/08 12:11:27 PM10/1/08 12:11:27 PM
Contents
xvi
Chapter 3: C# Language Foundations 61
Using Visual Studio 2008 61
Using the C# Compiler (csc.exe) 64
Dissecting the Program 66
Passing Arguments to Main() 68
Language Syntax 68
Keywords 68
Variables 69
Scope of Variables 71
Constants 74
Comments 74
XML Documentation 74
Data Types 78
Value Types 79
Reference Types 84
Enumerations 85
Arrays 87
Implicit Typing 88
Type Conversion 89
Flow Control 92
if-else Statement 92
switch Statement 94
Looping 96
for Loop 96

Nested for Loop 97
foreach 98
while and do-while Loops 99
Exiting from a Loop 99
Skipping an Iteration 102
Operators 102
Assignment Operators 103
Relational Operators 105
Logical Operators 106
Mathematical Operators 108
Operator Precedence 109
Preprocessor Directives 110
#define and #undef 111
#if, #else, #elif, and #endif 115
#warning and #error 117
#line 118
ftoc.indd xviftoc.indd xvi 10/1/08 12:11:28 PM10/1/08 12:11:28 PM
Contents
xvii
#region and #endregion 120
#pragma warning 122
Summary 123
Chapter 4: Classes and Objects 125
Classes 125
Defining a Class 126
Using Partial Classes 126
Creating an Instance of a Class (Object Instantiation) 127
Anonymous Types (C# 3.0) 128
Class Members 131
Function Members 134

Static Classes 156
System.Object Class 157
Testing for Equality 158
Implementing Equals 159
ToString() Method 161
Attributes 162
Structures 165
Summary 169
Chapter 5: Interfaces 171
Defining an Interface 172
Implementing an Interface 173
Implementing Multiple Interfaces 174
Extending Interfaces 175
Interface Casting 177
The is and as Operators 178
Overriding Interface Implementations 179
Summary 181
Chapter 6: Inheritance 183
Understanding Inheritance in C# 183
Implementation Inheritance 184
Abstract Class 186
Abstract Methods 186
Virtual Methods 189
Sealed Classes and Methods 191
Overloading Methods 192
ftoc.indd xviiftoc.indd xvii 10/1/08 12:11:28 PM10/1/08 12:11:28 PM
Contents
xviii
Overloading Operators 195
Extension Methods (C# 3.0) 198

Access Modifiers 200
Inheritance and Constructors 202
Calling Base Class Constructors 203
Interface Inheritance 204
Explicit Interface Members Implementation 208
Summary 211
Chapter 7: Delegates and Events 213
Delegates 213
Creating a Delegate 214
Delegates Chaining (Multicast Delegates) 217
Implementing Callbacks Using Delegates 220
Asynchronous Callbacks 222
Anonymous Methods and Lambda Expressions 225
Events 226
Handling Events 229
Implementing Events 232
Difference between Events and Delegates 235
Passing State Information to an Event Handler 237
Summary 240
Chapter 8: Strings and Regular Expressions 241
The System.String Class 241
Escape Characters 243
String Manipulations 247
String Formatting 254
The StringBuilder Class 257
Regular Expressions 259
Searching for a Match 259
More Complex Pattern Matching 261
Summary 263
Chapter 9: Generics 265

Understanding Generics 265
Generic Classes 268
Using the default Keyword in Generics 270
Advantages of Generics 271
ftoc.indd xviiiftoc.indd xviii 10/1/08 12:11:28 PM10/1/08 12:11:28 PM
Contents
xix
Using Constraints in a Generic Type 271
Generic Interfaces 275
Generic Structs 276
Generic Methods 276
Generic Operators 278
Generic Delegates 280
Generics and the .NET Framework Class Library 280
Using the LinkedList<T> Generic Class 284
System.Collections.ObjectModel 288
Summary 291
Chapter 10: Threading 293
The Need for Multithreading 293
Starting a Thread 295
Aborting a Thread 297
Passing Parameters to Threads 301
Thread Synchronization 303
Using Interlocked Class 304
Using C# Lock 304
Monitor Class 307
Thread Safety in Windows Forms 312
Using the BackgroundWorker Control 315
Testing the Application 320
Summary 320

Chapter 11: Files and Streams 321
Working with Files and Directories 321
Working with Directories 322
Working with Files Using the File and FileInfo Classes 326
Creating a FileExplorer 329
The Stream Class 331
BufferedStream 333
The FileStream Class 334
MemoryStream 337
NetworkStream Class 338
Cryptography 343
Hashing 344
Salted Hash 346
Encryption and Decryption 347
ftoc.indd xixftoc.indd xix 10/1/08 12:11:29 PM10/1/08 12:11:29 PM
Contents
xx
Compressions for Stream Objects 353
Compression 353
Decompression 354
Serialization 359
Binary Serialization 359
XML Serialization 365
Summary 375
Chapter 12: Exception Handling 377
Handling Exceptions 377
Handling Exceptions Using the try-catch Statement 378
Handling Multiple Exceptions 381
Throwing Exceptions Using the throw Statement 383
Rethrowing Exceptions 386

Exception Chaining 387
Using Exception Objects 389
The finally Statement 391
Creating Custom Exceptions 393
Summary 395
Chapter 13: Arrays and Collections 397
Arrays 397
Accessing Array Elements 400
Multidimensional Arrays 400
Arrays of Arrays: Jagged Arrays 402
Parameter Arrays 403
Copying Arrays 404
Collections Interfaces 404
Dynamic Arrays Using the ArrayList Class 405
Indexers and Iterators 407
Implementing IEnumerable<T> and IEnumerator<T> 410
Implementing Comparison Using IComparer<T> and IComparable<T> 413
Dictionary 420
Stacks 422
Queues 423
Summary 424
ftoc.indd xxftoc.indd xx 10/1/08 12:11:29 PM10/1/08 12:11:29 PM
Contents
xxi
Chapter 14: Language Integrated Query (LINQ) 425
LINQ Architecture 425
LINQ to Objects 426
Query Syntax versus Method Syntax and Lambda Expressions 429
LINQ and Extension Methods 430
LINQ and Anonymous Types 436

LINQ to DataSet 438
Reshaping Data 441
Aggregate Functions 442
Joining Tables 443
Typed DataSet 446
Detecting Null Fields 449
Saving the Result of a Query to a DataTable 449
LINQ to XML 450
Creating XML Trees 450
Querying Elements 452
An Example Using RSS 453
LINQ to SQL 458
Using the Object Relational Designer 458
Querying 460
Inserting New Rows 461
Updating Rows 463
Deleting Rows 463
Summary 465
Chapter 15: Assemblies and Versioning 467
Assemblies 467
Structure of an Assembly 467
Examining the Content of an Assembly 468
Single and Multi-File Assemblies 469
Understanding Namespaces and Assemblies 480
Private versus Shared Assemblies 486
Creating a Shared Assembly 488
The Global Assembly Cache 492
Putting the Shared Assembly into GAC 493
Making the Shared Assembly Visible in Visual Studio 495
Using the Shared Assembly 496

Summary 499
ftoc.indd xxiftoc.indd xxi 10/1/08 12:11:29 PM10/1/08 12:11:29 PM
Contents
xxii
Part II: Application Development Using C# 501
Chapter 16: Developing Windows Applications 503
The Project 503
Configuring the F TP Server 504
Creating the Application 506
Using Application Settings 508
Coding the Application 513
Building the Directory Tree and Displaying Images 515
Creating a New Directory 522
Removing a Directory 523
Uploading Photos 524
Deleting a Photo 525
Testing the Application 526
Adding Print Capability 526
Basics of Printing in .NET 526
Adding Print Support to the Project 527
Deploying the Application 533
Publishing the Application Using ClickOnce 534
Updating the Application 536
Programmatically Updating the Application 538
Rolling Back 541
Under the Hood: Application and Deployment Manifests 541
Summary 543
Chapter 17: Developing ASP.NET Web Applications 545
About ASP.NET 545
How ASP.NET Works 546

What Do You Need to Run ASP.NET? 546
Data Binding 547
Modeling Databases Using LINQ to SQL 548
Data Binding Using the GridView Control 549
Displaying Publisher’s Name 554
Displaying Titles from a Selected Publisher 555
Making the Publisher Field Editable 559
Building Responsive Applications Using AJAX 560
AJAX Control Toolkit 561
AJAX-Enabling a Page Using the ScriptManager Control 563
Using the UpdatePanel Control 563
Using Triggers to Cause an Update 564
ftoc.indd xxiiftoc.indd xxii 10/1/08 12:11:30 PM10/1/08 12:11:30 PM
Contents
xxiii
Displaying Progress Using the UpdateProgress Control 565
Displaying a Modal Dialog Using the ModalPopupExtender Control 566
Summary 572
Chapter 18: Developing Windows Mobile Applications 573
The Windows Mobile Platform 574
Developing Windows Mobile Applications Using the .NET Compact Framework 576
Obtaining the Appropriate SDKs and Tools 578
Building the RSS Reader Application 580
Building the User Interface 581
Creating the Helper Methods 583
Wiring All the Event Handlers 589
Testing Using Emulators 596
Testing Using Real Devices 597
Deploying the Application 598
Creating a CAB File 598

Creating a Setup Application 603
Summary 616
Chapter 19: Developing Silverlight Applications 617
The State of Silverlight 617
Obtaining the Tools 619
Architecture of Silverlight 620
Building a Silverlight UI Using XAML 621
Creating a Bare-Bones Silverlight Application 621
Understanding XAML 623
Crafting XAML Using Expression Blend 2 635
Silverlight 1.0 645
Animation — Part 1 645
Animations — Part 2 650
Playing Media 654
Creating Your Own Media Player 663
Silverlight 2.0 675
Creating the Project Using Visual Studio 2008 676
Summary 694
ftoc.indd xxiiiftoc.indd xxiii 10/1/08 12:11:30 PM10/1/08 12:11:30 PM

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×