Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

c# 4 0 in a nutshell 4ed (o'reilly)
Nội dung xem thử
Mô tả chi tiết
C# 4.0
IN A NUTSHELL
C# 4.0
IN A NUTSHELL
Fourth Edition
Joseph Albahari and Ben Albahari
Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo
C# 4.0 in a Nutshell, Fourth Edition
by Joseph Albahari and Ben Albahari
Copyright © 2010 Joseph Albahari and Ben Albahari. 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 (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or
Editor: Laurel R.T. Ruma
Production Editor: Loranah Dimant
Copyeditor: Audrey Doyle
Proofreader: Colleen Toporek
Indexer: John Bickelhaupt
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
March 2002: First Edition.
August 2003: Second Edition.
September 2007: Third Edition.
January 2010: Fourth Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. C# 4.0 in a Nutshell, the image of a Numidian crane, and related
trade dress are trademarks of O’Reilly Media, Inc.
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.
ISBN: 978-0-596-80095-6
[M]
1263924338
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1. Introducing C# and the .NET Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Object Orientation 1
Type Safety 2
Memory Management 2
Platform Support 3
C#’s Relationship with the CLR 3
The CLR and .NET Framework 3
What’s New in C# 4.0 5
2. C# Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
A First C# Program 7
Syntax 10
Type Basics 12
Numeric Types 21
Boolean Type and Operators 28
Strings and Characters 30
Arrays 32
Variables and Parameters 36
Expressions and Operators 44
Statements 48
Namespaces 56
3. Creating Types in C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Classes 63
Inheritance 76
The object Type 85
v
Structs 89
Access Modifiers 90
Interfaces 92
Enums 97
Nested Types 100
Generics 101
4. Advanced C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Delegates 115
Events 124
Lambda Expressions 130
Anonymous Methods 134
try Statements and Exceptions 134
Enumeration and Iterators 143
Nullable Types 148
Operator Overloading 153
Extension Methods 157
Anonymous Types 160
Dynamic Binding 161
Attributes 169
Unsafe Code and Pointers 170
Preprocessor Directives 174
XML Documentation 176
5. Framework Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
The CLR and Core Framework 183
Applied Technologies 187
6. Framework Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
String and Text Handling 193
Dates and Times 206
Dates and Time Zones 213
Formatting and Parsing 219
Standard Format Strings and Parsing Flags 225
Other Conversion Mechanisms 232
Globalization 235
Working with Numbers 237
Enums 240
Tuples 244
The Guid Struct 245
Equality Comparison 245
Order Comparison 255
Utility Classes 258
vi | Table of Contents
7. Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Enumeration 263
The ICollection and IList Interfaces 271
The Array Class 273
Lists, Queues, Stacks, and Sets 282
Dictionaries 292
Customizable Collections and Proxies 298
Plugging in Equality and Order 304
8. LINQ Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Getting Started 311
Fluent Syntax 314
Query Expressions 320
Deferred Execution 324
Subqueries 330
Composition Strategies 333
Projection Strategies 337
Interpreted Queries 339
LINQ to SQL and Entity Framework 346
Building Query Expressions 361
9. LINQ Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Overview 369
Filtering 371
Projecting 375
Joining 387
Ordering 394
Grouping 397
Set Operators 400
The Zip Operator 401
Conversion Methods 402
Element Operators 404
Aggregation Methods 406
Quantifiers 411
Generation Methods 412
10. LINQ to XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Architectural Overview 413
X-DOM Overview 414
Instantiating an X-DOM 418
Navigating and Querying 420
Updating an X-DOM 425
Working with Values 428
Documents and Declarations 431
Names and Namespaces 434
Table of Contents | vii
Annotations 440
Projecting into an X-DOM 441
11. Other XML Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
XmlReader 448
XmlWriter 457
Patterns for Using XmlReader/XmlWriter 459
XmlDocument 463
XPath 466
XSD and Schema Validation 471
XSLT 474
12. Disposal and Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
IDisposable, Dispose, and Close 475
Automatic Garbage Collection 480
Finalizers 482
How the Garbage Collector Works 487
Managed Memory Leaks 491
Weak References 494
13. Diagnostics and Code Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Conditional Compilation 499
Debug and Trace Classes 502
Code Contracts Overview 506
Preconditions 510
Postconditions 514
Assertions and Object Invariants 517
Contracts on Interfaces and Abstract Methods 518
Dealing with Contract Failure 519
Selectively Enforcing Contracts 521
Static Contract Checking 523
Debugger Integration 524
Processes and Process Threads 525
StackTrace and StackFrame 526
Windows Event Logs 528
Performance Counters 530
The Stopwatch Class 535
14. Streams and I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
Stream Architecture 537
Using Streams 539
Stream Adapters 552
File and Directory Operations 559
Memory-Mapped Files 569
Compression 571
viii | Table of Contents
Isolated Storage 573
15. Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
Network Architecture 579
Addresses and Ports 581
URIs 582
Request/Response Architecture 584
HTTP-Specific Support 592
Writing an HTTP Server 597
Using FTP 600
Using DNS 602
Sending Mail with SmtpClient 603
Using TCP 604
Receiving POP3 Mail with TCP 606
16. Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
Serialization Concepts 609
The Data Contract Serializer 613
Data Contracts and Collections 622
Extending Data Contracts 625
The Binary Serializer 628
Binary Serialization Attributes 630
Binary Serialization with ISerializable 634
XML Serialization 637
17. Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
What’s in an Assembly? 647
Strong Names and Assembly Signing 652
Assembly Names 655
Authenticode Signing 657
The Global Assembly Cache 661
Resources and Satellite Assemblies 663
Resolving and Loading Assemblies 671
Deploying Assemblies Outside the Base Folder 675
Packing a Single-File Executable 676
Working with Unreferenced Assemblies 678
18. Reflection and Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
Reflecting and Activating Types 682
Reflecting and Invoking Members 688
Reflecting Assemblies 700
Working with Attributes 701
Dynamic Code Generation 707
Emitting Assemblies and Types 714
Emitting Type Members 717
Table of Contents | ix
Emitting Generic Methods and Types 723
Awkward Emission Targets 725
Parsing IL 728
19. Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
The Dynamic Language Runtime 735
Numeric Type Unification 737
Dynamic Member Overload Resolution 738
Implementing Dynamic Objects 744
Interoperating with Dynamic Languages 747
20. Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
Permissions 751
Code Access Security (CAS) 755
Allowing Partially Trusted Callers 758
The Transparency Model in CLR 4.0 761
Sandboxing Another Assembly 769
Operating System Security 772
Identity and Role Security 775
Cryptography Overview 776
Windows Data Protection 777
Hashing 778
Symmetric Encryption 780
Public Key Encryption and Signing 784
21. Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
Threading’s Uses and Misuses 789
Getting Started 791
Thread Pooling 800
Synchronization 805
Locking 808
Thread Safety 817
Nonblocking Synchronization 825
Signaling with Event Wait Handles 832
Signaling with Wait and Pulse 840
The Barrier Class 849
The Event-Based Asynchronous Pattern 851
BackgroundWorker 852
Interrupt and Abort 855
Safe Cancellation 857
Lazy Initialization 860
Thread-Local Storage 862
Reader/Writer Locks 865
Timers 869
x | Table of Contents
22. Parallel Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873
Why PFX? 874
PLINQ 877
The Parallel Class 892
Task Parallelism 898
Working with AggregateException 912
Concurrent Collections 914
SpinLock and SpinWait 920
23. Asynchronous Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
Why Asynchronous Methods Exist 927
Asynchronous Method Signatures 928
Asynchronous Methods Versus Asynchronous Delegates 930
Using Asynchronous Methods 930
Asynchronous Methods and Tasks 934
Writing Asynchronous Methods 937
Fake Asynchronous Methods 940
Alternatives to Asynchronous Methods 941
24. Application Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
Application Domain Architecture 943
Creating and Destroying Application Domains 945
Using Multiple Application Domains 946
Using DoCallBack 948
Monitoring Application Domains 949
Domains and Threads 950
Sharing Data Between Domains 951
25. Native and COM Interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
Calling into Native DLLs 957
Type Marshaling 958
Callbacks from Unmanaged Code 961
Simulating a C Union 962
Shared Memory 963
Mapping a Struct to Unmanaged Memory 965
COM Interoperability 969
Calling a COM Component from C# 971
Embedding Interop Types 975
Primary Interop Assemblies 975
Exposing C# Objects to COM 976
26. Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977
Regular Expression Basics 977
Quantifiers 982
Zero-Width Assertions 983
Table of Contents | xi
Groups 985
Replacing and Splitting Text 987
Cookbook Regular Expressions 988
Regular Expressions Language Reference 992
Appendix: C# Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 997
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005
xii | Table of Contents
Preface
C# 4.0 further enhances Microsoft’s flagship programming language with muchrequested features—including support for dynamic programming, type parameter
variance, and optional and named parameters. At the same time, the CLR and .NET
Framework have grown to include a rich set of features for parallel programming,
code contracts, and a new code security model.
The price of this growth is that there’s more than ever to learn. Although tools such
as Microsoft’s IntelliSense—and online references—are excellent in helping you on
the job, they presume an existing map of conceptual knowledge. This book provides
exactly that map of knowledge in a concise and unified style—free of clutter and
long introductions.
Like the previous edition, C# 4.0 in a Nutshell is organized entirely around concepts
and use cases, making it friendly both to sequential reading and to random browsing.
It also plumbs significant depths while assuming only basic background
knowledge—making it accessible to intermediate as well as advanced readers.
This book covers C#, the CLR, and the core Framework assemblies. We’ve chosen
this focus to allow space for difficult topics such as concurrency, security, and application domains—without compromising depth or readability. Features new to
C# 4.0 and the associated Framework are flagged so that you can also use this book
as a C# 3.0 reference.
Intended Audience
This book targets intermediate to advanced audiences. No prior knowledge of C#
is required, but some general programming experience is necessary. For the beginner, this book complements, rather than replaces, a tutorial-style introduction to
programming.
xiii