Tải bản đầy đủ (.pdf) (1,293 trang)

introducing visual c 2010

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 (24.12 MB, 1,293 trang )

www.it-ebooks.info

Introducing
Visual C# 2010








  
Adam Freeman

www.it-ebooks.info
Introducing Visual C# 2010
Copyright © 2010 by Adam Freeman
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 information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-3171-4
ISBN-13 (electronic): 978-1-4302-3172-1
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of
the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights.


President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham
Technical Reviewer: Damien Foggon
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick,
Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank
Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Anne Collett and Kelly Moritz
Copy Editor: Kim Wimpsett and Mary Behr
Compositor: Bytheway Publishing Services
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
, or visit www.springeronline.com.
For information on translations, please e-mail , or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
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
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com.

www.it-ebooks.info

iv
Contents at a Glance
 About the Author xxxii

 About the Technical Reviewer xxxiii
 Acknowledgments xxxiv
PART 1    Getting Started 1
 Chapter 1: Introduction 3
 Chapter 2: Getting Ready 7
 Chapter 3: Understanding C# and the .NET Framework 17
PART 2    The C# Language 31
 Chapter 4: C# Fundamentals and Keyword Reference 33
 Chapter 5: Numeric and Boolean Types 91
 Chapter 6: Classes and Objects 131
 Chapter 7: Fields 183
 Chapter 8: Properties, Indexers, and Operators 203
 Chapter 9: Methods 229
 Chapter 10: Delegates, Events, and Anonymous Methods 305
 Chapter 11: Namespaces 337
 Chapter 12: Interfaces, Structs, and Enums 355
 Chapter 13: Arrays 385
 Chapter 14: Exceptions 419
 Chapter 15: Generic and Anonymous Types 453
 Chapter 16: Strings and Characters 481
www.it-ebooks.info
 CONTENTS AT A GLANCE
v
 Chapter 17: Attributes 519
 Chapter 18: Garbage Collection 539
PART 3    The .NET Class Library 549
 Chapter 19: Collections 551
 Chapter 20: Files, Streams, and IO 621
 Chapter 21: Networking & WCF 675
 Chapter 22: Time & Dates 711

 Chapter 23: Serialization 735
 Chapter 24: Serialization 735
 Chapter 25: Asynchronous Methods and Parallel Loops 815
 Chapter 26: Other Useful Features and Classes 833
PART 4    Data and Databases 861
 Chapter 27: LINQ to Objects 863
 Chapter 28: Parallel LINQ 915
 Chapter 29: LINQ to XML 925
 Chapter 30: LINQ to Entities 965
 Chapter 31: LINQ to DataSet 1001
PART 5    User Interfaces 1031
 Chapter 32: Windows Forms 1033
 Chapter 33: Windows Presentation Foundation 1069
 Chapter 34: ASP.NET 1099
 Chapter 35: Silverlight 1125
PART 6    Advanced Topics 1159
 Chapter 36: Windows Integration 1161
 Chapter 37: Cryptography and Security 1185
 Chapter 38: Testing and Debugging 1201
 Index 1231
www.it-ebooks.info

vi
Contents
 About the Authors xxxii
 About the Technical Reviewers xxxiii
 Acknowledgments xxxiv
PART 1    Getting Started 1
 Chapter 1: Introduction 3
Who Should Read This Book? 3

What Is Covered in This Book? 3
What Do You Need to Read This Book? 4
What Is the Structure of This Book? 4
What Is in Each Chapter? 4
Getting the Example Code 5
Finding More Information 6
The MSDN C# Programming Guide 6
Online Forums 6
Other Books 6
Summary 6
 Chapter 2: Getting Ready 7
Installing the Software 7
Installing Visual Studio 2010 7
Installing SQL Server 2008 9
Installing the Silverlight Tools 10
Downloading the Sample Code and Data 10
www.it-ebooks.info
 CONTENTS
vii
Creating Your First C# Project 10
Creating the Project 11
Editing the Code 13
Compiling and Running the Program 14
Features That I Use Before Explaining Them 14
The using statements 14
The namespace statement 15
The class statement 15
The Main method 15
The Code Comments 16
The Console.WriteLine and Console.ReadLine methods 16

Summary 16
 Chapter 3: Understanding C# and the .NET Framework 17
C# and the .NET Framework at a Glance 17
Introducing C# 17
Introducing the .NET Framework 18
The Relationship between C# and the .NET Framework 19
Understanding Assemblies 20
The Key Features of C# and the .NET Framework 22
Understanding Object-Orientation 22
Understanding Type Safety 22
Understanding Automatic Memory Management 23
Understanding the Just-In-Time Compiler 23
Understanding Parallel Processing 23
Understanding Unmanaged/Native Code Support 24
Understanding the .NET Technology Spectrum 24
Understanding .NET Cross-Platform Support 29
Summary 30
www.it-ebooks.info
 CONTENTS
viii
PART 2    The C# Language 31
 Chapter 4: C# Fundamentals and Keyword Reference 33
Language Fundamentals 33
A Simple C# Program 33
C# Syntax 34
Types 41
Common Programming Tasks 46
Assigning Values 46
Making Comparisons 47
Performing Selections 49

Iterating Data Items 53
Keyword and Operator Reference 60
Type Keywords 61
Modifiers 69
Selection Keywords 75
Iterator Keywords 75
Jump Keywords 76
Exception Handling Keywords 77
Arithmetic Overflow Keywords 78
Synchronization Keywords 79
Parameter Keywords 79
Namespace Keywords 81
Literal Keywords 82
Object Keywords 83
LINQ Keywords 84
Other Keywords 84
Operators 87
Summary 89

www.it-ebooks.info
 CONTENTS
ix
 Chapter 5: Numeric and Boolean Types 91
Numeric Types 92
Using Numeric Literals 93
Implicit and Explicit Numeric Type Conversions 98
Using Overflow Checking 101
Using Struct Members 103
Using Numeric Operators 109
Arithmetic Operators 109

Unary Operators 113
Relational Operators 116
Logical Operators 118
Assignment Operators 122
Working with Very Large Integer Values 126
The Boolean Type 127
Using Boolean Literals 127
Using Boolean Results 128
Using Struct Members 129
Summary 130
 Chapter 6: Classes and Objects 131
Creating a Basic Class 132
Adding Features to a Class 133
Creating Objects from Classes 136
Using Objects 139
Class Inheritance 150
Understanding Inheritance 153
Understanding Encapsulation 159
Understanding Polymorphism 160

www.it-ebooks.info
 CONTENTS
x
Casting Objects and Type Checking 165
Implicit vs. Explicit Casting. 165
Type Conversion Exceptions. 169
Avoiding Explicit Cast Exceptions. 170
Boxing and Unboxing. 173
Using Nested Classes 175
Using Class Modifiers 176

Creating Static Classes. 176
Creating Abstract Classes . 178
Creating Sealed Classes. 179
Creating Partial Classes. 179
Using Access Modifiers . 180
Summary 181
 Chapter 7: Fields 183
Defining and Using Fields 184
Defining Fields. 184
Initializing Fields. 184
Reading and Updating Fields. 186
The Fourth Stage of the Life Cycle . 193
Applying Field Modifiers 193
Creating Static Fields . 194
Creating Read-Only Fields. 196
Applying Access Modifiers . 199
Hiding Base Class Fields . 199
Using the volatile Keyword. 201
Summary 201

www.it-ebooks.info
 CONTENTS
xi
 Chapter 8: Properties, Indexers, and Operators 203
Creating a Property 204
Creating a Field-Backed Property 204
Using a Property 207
Creating an Automatically Implemented Property 208
Creating an Asymmetric Property 209
Creating a Computed Property 209

Mapping a Property Type to a Field Type 210
Using Access Modifiers 210
Using Other Modifiers 211
Creating an Indexer 215
Using Multiple Indexers 216
Creating a Validating Indexer 217
Creating an Indexer with Multiple Arguments 218
Creating Custom Operators 219
Creating Custom Unary Operators 219
Creating Custom Binary Operators 221
Creating Custom Conversion Operators 225
Summary 227
 Chapter 9: Methods 229
Creating and Using a Simple Method 231
Defining the Method Name 232
Defining the Result Type 232
Defining the Parameters 233
Defining the Modifiers 234
Defining the Method Body 237
Using the Methods 238
www.it-ebooks.info
 CONTENTS
xii
Understanding Parameters 239
Using Value Parameters 239
Using Reference Parameters 243
Using Output Parameters 245
Using Parameter Arrays 247
Using Optional Parameters 249
Using Named Parameters 250

Understanding Method Bodies 251
Using Local Variables 251
Using Method Results 256
Understanding Method Modifiers 257
Using Access Modifiers 257
Creating Static Methods 257
Creating Virtual Methods 258
Creating Sealed Methods 258
Creating Abstract Methods 259
Overloading Methods 259
Hiding and Overriding Methods 262
Hiding Methods 263
Overriding Methods 265
Sealing Methods 267
Understanding Method Specialization 268
Special Methods 269
The Main Method 269
Constructors 272
Destructors 290
Iterator Blocks 291
Partial Methods 296
Abstract Methods 299
www.it-ebooks.info
 CONTENTS
xiii
Extension Methods 301

Summary 304
 Chapter 10: Delegates, Events, and Anonymous Methods 305
Using Delegates 306

Using Delegates for Callbacks 308
Multicasting with Delegates 310
Delegating Selectively 312
Interrogating Delegates 313
Using Events 315
Defining and Publishing EventHandler Pattern Events 317
Creating Nongeneric Events 322
Creating Events Without Custom Data 323
Applying Modifiers to Events 325
Using Action and Func Delegates 326
Using Action Delegates 326
Using Func Delegates 328
Anonymous Methods 329
Capturing Outer Variables 331
Lambda Expressions 334
Summary 336
 Chapter 11: Namespaces 337
Consuming Namespaces 337
Using Fully Qualified Names 338
Importing Namespaces 339
Creating Namespaces 340
Nesting Namespaces 342
Logically Nesting Namespaces 343
Spreading Namespaces Across Files 344
www.it-ebooks.info
 CONTENTS
xiv
Adding Types to Existing Namespaces 346

Disambiguating Namespaces and Types 347

Disambiguation with Fully Qualified Names 349
Disambiguating with Aliases 349
Aliasing Namespaces 350
Resolving Type or Namespace Hiding 351
Summary 353
 Chapter 12: Interfaces, Structs, and Enums 355
Using Interfaces 356
Defining and Using a Simple Interface 356
Specifying Interface Members 358
Deriving Interfaces 362
Defining a Partial Interface 365
Implementing Interfaces 365
Using Structs 371
Defining and Instantiating a Struct 371
Differences Between Structs and Classes 374
Copying a Struct 376
Using an Enum 380
Defining an Enum 380
Using an Enum 381
Using Underlying Types and Numeric Values 382
Combining Enum Values 383
Summary 384
 Chapter 13: Arrays 385
Defining and Initializing Arrays 387
Getting and Setting Array Values 389
Using Array Initializers 391
www.it-ebooks.info
 CONTENTS
xv
Enumerating Arrays 393

Enumerating with a for Loop 393
Enumerating with a foreach Loop 395
Enumerating Using IEnumerator and IEnumerator<T> 396
Breaking from Enumerations 398
Using System.Array Members 400
Sorting Arrays 400
Processing All of the Elements in an Array 401
Resizing and Copying an Array 402
Finding Items in an Array 406
Using Arrays with LINQ 408
Using Arrays as Collections 409
Using Multidimensional Arrays 409
Using Rectangular Arrays 410
Using Jagged Arrays 415
Summary 418
 Chapter 14: Exceptions 419
Handling Exceptions 420
Using try Statements and catch Clauses 421
Handling Different Exception Types 424
Nesting try Statements 427
Using Exception Members 427
Using finally Clauses 430
Throwing Exceptions 432
Rethrowing Exceptions 436
Creating and Throwing Custom Exceptions 438
Throwing Meaningful Exceptions 441
Summary 451
www.it-ebooks.info
 CONTENTS
xvi

 Chapter 15: Generic and Anonymous Types 453
Using Generic Types 454
Defining a Generic Class 456
Creating Objects from Generic Classes 456
Implementing and Using Generic Class Members 457
Defining Multiple Parameter Types 460
Casting from Parameterized Types 461
Constraining Parameterized Types 462
Defining a Method-Specific Parameterized Type 465
Deriving from a Generic Base Class 467
Creating Generic Interfaces 471
Creating Generic Structs 472
Type Variance 472
Using the default Keyword 477
Using Anonymous Types 478
Summary 480
 Chapter 16: Strings and Characters 481
Working with Characters 482
Expressing Characters Using Literals 482
Performing Operations on Characters 483
Using Struct Members 484
Using Strings 486
Expressing Strings Using String Literals 486
Performing Operations on Strings 488
Using Regular Expressions 495
Using Class Members 496
www.it-ebooks.info
 CONTENTS
xvii
Using the StringBuilder Class 502

Creating a StringBuilder Object 502
Using a StringBuilder Object 502
Formatting Strings 507
Using Composite Formatting 507
Formatting Types 511
Creating String Representations of Custom Types 514
Performing Custom Composite Formatting 516
Summary 518
 Chapter 17: Attributes 519
Using Attributes 519
Applying Attributes with Parameters 521
Testing for an Attribute 522
Testing for an Attribute Applied to a Class 522
Testing for an Attribute Applied to a Field 525
Testing for an Attribute Applied to a Property 528
Testing for an Attribute Applied to a Method 530
Creating a Custom Attribute 532
Using a Custom Attribute 533
Defining Properties in a Custom Attribute 535
Controlling How a Custom Attribute Can Be Used 535
Controlling Attribute Inheritance 537
Summary 538
 Chapter 18: Garbage Collection 539
Explicitly Running the Garbage Collector 540
Implementing a Destructor 541
Destructors vs. Finalizers 542
Problems with Destructors 543
www.it-ebooks.info
 CONTENTS
xviii

Using Disposal 544
Using Weak References 546
Summary 547
PART 3    The .NET Class Library 549
 Chapter 19: Collections 551
The ICollection<T> Interface 553
Generic Lists 554
The IList<T> Interface 555
The List<T> Collection 556
The LinkedList<T> Collection 575
The SortedList<TKey, TVal> Collection 581
Generic Dictionaries 585
The IDictionary<TKey, TVal> Interface 586
The KeyValuePair<TKey, TVal> Structure 588
The Dictionary<TKey, TVal> Collection 589
The SortedDictionary<TKey, TVal> Collection 593
Generic Sets 595
The ISet<T> Interface 595
The HashSet<T> Collection 597
The SortedSet<T> Collection 599
Generic Queues and Stacks 602
The Queue<T> Collection 602
The Stack<T> Collection 604
Other Generic Collection Interfaces 606
The IComparer<T> Interface 606
The IEqualityComparer<T> Interface 608
Treating Arrays as Collections 609
www.it-ebooks.info
 CONTENTS
xix

Creating Constrained Collections 613
Read-Only Lists 613
Other Read-Only Collections 614
Legacy Collections 617
Summary 619
 Chapter 20: Files, Streams, and IO 621
Working with Files and Directories 622
Using the System.IO.Directory Class 622
Using the FileInfo and DirectoryInfo Classes 630
Using the System.IO.File Class 639
Using the System.IO.Path Class 643
Monitoring for Changes 645
Working with Streams, Readers, and Writers 650
Using Streams 650
Using Readers and Writers 666
Summary 673
 Chapter 21: Networking & WCF 675
Requesting Data 675
Using WebClient Members to Configure a Request 677
Using WebClient Members to Retrieve Data 679
Using WebClient Events 682
Programming with Sockets 684
Creating a Simple TCP Client & Server 684
Writing a Parallel Server 691
The Windows Communication Foundation 693
Creating the WCF Server 694
Creating the WCF Client 697
www.it-ebooks.info
 CONTENTS
xx

Other Useful Network Classes 700
Writing a Simple Web Server. 700
Using Connectionless Networking. 704
Using the Domain Name System . 707
Summary 709
 Chapter 22: Time & Dates 711
Measuring Small Amounts of Time 712
Working with Periods of Time 715
Creating and Using TimeSpan Values. 715
Performing Operations on TimeSpan Values. 719
Formatting TimeSpan Strings. 720
Working with Particular Dates and Times 723
Creating and Using DateTime Values . 724
Performing Operations on DateTime Values. 727
Formatting DateTime Strings. 730
Summary 733
 Chapter 23: Serialization 735
Using Binary Serialization 736
Serializing Graphs of Objects . 739
Serializing Multiple Objects to a Single Stream . 741
Selectively Serializing Fields. 744
Using Serialization Callbacks . 745
Version Tolerance. 748
Using SOAP Serialization 752
Version Tolerance. 754
Serializing Generic Objects. 755
Using XML Serialization 755
Selectively Serializing Fields. 757

www.it-ebooks.info

 CONTENTS
xxi
Mapping Members to Elements and Attributes 758

Changing the Name for Attributes and Elements 759
Using Data Contract Serialization 760
Preparing a Class for Data Contract Serialization 760
Generating Portable XML 761
Generating .NET-specific XML 762
Generating JSON 764
Summary 765
 Chapter 24: Serialization 735
Understanding Single- and Multi-Threaded Execution 768
Getting Started with Tasks 772
Creating a Task 772
Starting a Task 773
Waiting for a Task 774
Getting Results from Tasks 776
Passing Parameters to a Task 778
Getting the Status of a Task 780
Using the Status Properties 782
Canceling Tasks 782
Checking and Throwing in a Single Statement 784
Cancelling Multiple Tasks 786
Handling Task Exceptions 787
Handling an Exception in a Task Body 787
Handling an Exception from a Trigger Method 789
Dealing with Exceptions using Task Properties 792
Using a Custom Exception Escalation Policy 794
Chaining Tasks Together 796

Creating a Simple Continuation 796
www.it-ebooks.info
 CONTENTS
xxii
Getting Details of the Antecedent 797

Providing a Continuation Result 798
Creating Chains of Continuations 800
Creating Selective Continuations 801
Sharing Data between Tasks 803
Understanding a Critical Region 806
Creating a Critical Region 806
Avoiding Synchronization 808
Using Concurrent Collections 809
Summary 813
 Chapter 25: Asynchronous Methods and Parallel Loops 815
Using Asynchronous Methods 816
Using Pre-Built Asynchronous Methods 816
Asynchronously Calling Any Method 819
Waiting for an Asynchronous Method to Complete 820
Mixing Asynchronous Methods and Tasks 823
Using Parallel Loops 824
Creating a Parallel ForEach Loop 824
Creating a Parallel For Loop 826
Breaking and Stopping Parallel Loops 827
Summary 831
 Chapter 26: Other Useful Features and Classes 833
Converting Between Types 834
Returning Multiple Results from Methods Using Tuples 836
Aliasing Generic Types 839

Using Nullable Types 841
Using the Null-Coalescing Operator 842
www.it-ebooks.info
 CONTENTS
xxiii
Working with the Console 843
Reading from and Writing to the Console 843
Making the Console Beep 846
Modifying the Appearance of the Console 846
Generating Random Numbers 848
Converting Strings to and from Bytes 849
Getting Environment Information 850
Performing Math Operations 852
Using Conditional Compilation 853
Using Visual Studio to Define Symbols 855
Conditionally Compiling Methods 856
Checking Network Connectivity 857
Listening for Connectivity Changes 859
Summary 860
PART 4    Data and Databases 861
 Chapter 27: LINQ to Objects 863
Performing a Simple LINQ Query 864
Understanding LINQ to Objects Data Sources 866
Understanding Query Results 867
Understanding Query Types 870
Performing LINQ Operations 874
Filtering Data 874
Projecting Data 876
Ordering Data 881
Grouping Data 885

Using Method Syntax 891
Understanding Deferred Execution 895
Reusing Queries 895
www.it-ebooks.info
 CONTENTS
xxiv
Referring to Variables 896

Forcing Immediate Execution 897
Converting Query Results 899
Using Legacy Collections as LINQ Data Sources 902
Explicitly Specifying the Range Variable Type 902
Using Cast and OfType Extension Methods 903
Performing Advanced LINQ Operations 905
Aggregating Data 905
Joining Data 907
Creating Combinations of Data 910
Creating Additional Range Variables 911
Summary 913
 Chapter 28: Parallel LINQ 915
Performing a Parallel LINQ Query 915
Understanding PLINQ Result Ordering 918
Preserving Order in a PLINQ query 920
Forcing Parallel Execution 921
Performing Queries without Results 922
Summary 923
 Chapter 29: LINQ to XML 925
Using the LINQ XML Classes 926
Creating XML Declaratively 926
Populating an XElement or XDocument with an IEnumerable 933

Reading and Writing XML Files 934
Processing XML Declaratively 936
Modifying XML 940
Using LINQ to XML Queries 944
Querying XML for Data 945
www.it-ebooks.info
 CONTENTS
xxv
Creating XML from LINQ Queries 946

Create Objects from XML 949
Modifying and Transforming XML Data 950
Sorting XML 957
Grouping XML 958
Using Parallel LINQ to Process XML 960
Summary 963
 Chapter 30: LINQ to Entities 965
Getting Ready 966
Preparing the Database 967
Creating the Model 967
Using LINQ to Entities 973
Using the Data Model Context 974
Using Table Properties and Row Objects 975
Understanding the IQueryable<T> Interface 977
Enumerating the Results 978
Navigating Using Foreign Key Relationships 979
Querying Using Navigation Properties 982
Using Navigation Data Efficiently 983
Performing Common Database Operations 985
Querying Data 985

Inserting Data into the Database 993
Updating Data in the Database 996
Deleting Data 998
Enabling Concurrency Checking 999
Summary 1000
 Chapter 31: LINQ to DataSet 1001
Connecting to and Querying a Database 1002
www.it-ebooks.info

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

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