logo资料库

C# 6.0 in a Nutshell.pdf

第1页 / 共1133页
第2页 / 共1133页
第3页 / 共1133页
第4页 / 共1133页
第5页 / 共1133页
第6页 / 共1133页
第7页 / 共1133页
第8页 / 共1133页
资料共1133页,剩余部分请下载后查看
Copyright
Table of Contents
Preface
Intended Audience
How This Book Is Organized
What You Need to Use This Book
Conventions Used in This Book
Using Code Examples
Safari® Books Online
How to Contact Us
Acknowledgments
Joseph Albahari
Ben Albahari
Chapter 1. Introducing C# and the .NET Framework
Object Orientation
Type Safety
Memory Management
Platform Support
C#’s Relationship with the CLR
The CLR and .NET Framework
C# and Windows Runtime
What’s New in C# 6.0
What Was New in C# 5.0
What Was New in C# 4.0
What Was New in C# 3.0
Chapter 2. C# Language Basics
A First C# Program
Compilation
Syntax
Identifiers and Keywords
Literals, Punctuators, and Operators
Comments
Type Basics
Predefined Type Examples
Custom Type Examples
Conversions
Value Types Versus Reference Types
Predefined Type Taxonomy
Numeric Types
Numeric Literals
Numeric Conversions
Arithmetic Operators
Increment and Decrement Operators
Specialized Integral Operations
8- and 16-Bit Integrals
Special Float and Double Values
double Versus decimal
Real-Number Rounding Errors
Boolean Type and Operators
Bool Conversions
Equality and Comparison Operators
Conditional Operators
Strings and Characters
Char Conversions
String Type
Arrays
Default Element Initialization
Multidimensional Arrays
Simplified Array Initialization Expressions
Bounds Checking
Variables and Parameters
The Stack and the Heap
Definite Assignment
Default Values
Parameters
var—Implicitly Typed Local Variables
Expressions and Operators
Primary Expressions
Void Expressions
Assignment Expressions
Operator Precedence and Associativity
Operator Table
Null Operators
Null-Coalescing Operator
Null-conditional operator (C# 6)
Statements
Declaration Statements
Expression Statements
Selection Statements
Iteration Statements
Jump Statements
Miscellaneous Statements
Namespaces
The using Directive
using static (C# 6)
Rules Within a Namespace
Aliasing Types and Namespaces
Advanced Namespace Features
Chapter 3. Creating Types in C#
Classes
Fields
Methods
Instance Constructors
Object Initializers
The this Reference
Properties
Indexers
Constants
Static Constructors
Static Classes
Finalizers
Partial Types and Methods
The nameof operator (C# 6)
Inheritance
Polymorphism
Casting and Reference Conversions
Virtual Function Members
Abstract Classes and Abstract Members
Hiding Inherited Members
Sealing Functions and Classes
The base Keyword
Constructors and Inheritance
Overloading and Resolution
The object Type
Boxing and Unboxing
Static and Runtime Type Checking
The GetType Method and typeof Operator
The ToString Method
Object Member Listing
Structs
Struct Construction Semantics
Access Modifiers
Examples
Friend Assemblies
Accessibility Capping
Restrictions on Access Modifiers
Interfaces
Extending an Interface
Explicit Interface Implementation
Implementing Interface Members Virtually
Reimplementing an Interface in a Subclass
Interfaces and Boxing
Enums
Enum Conversions
Flags Enums
Enum Operators
Type-Safety Issues
Nested Types
Generics
Generic Types
Why Generics Exist
Generic Methods
Declaring Type Parameters
typeof and Unbound Generic Types
The default Generic Value
Generic Constraints
Subclassing Generic Types
Self-Referencing Generic Declarations
Static Data
Type Parameters and Conversions
Covariance
Contravariance
C# Generics Versus C++ Templates
Chapter 4. Advanced C#
Delegates
Writing Plug-in Methods with Delegates
Multicast Delegates
Instance Versus Static Method Targets
Generic Delegate Types
The Func and Action Delegates
Delegates Versus Interfaces
Delegate Compatibility
Events
Standard Event Pattern
Event Accessors
Event Modifiers
Lambda Expressions
Explicitly Specifying Lambda Parameter Types
Capturing Outer Variables
Anonymous Methods
try Statements and Exceptions
The catch Clause
The finally Block
Throwing Exceptions
Key Properties of System.Exception
Common Exception Types
The TryXXX Method Pattern
Alternatives to Exceptions
Enumeration and Iterators
Enumeration
Collection Initializers
Iterators
Iterator Semantics
Composing Sequences
Nullable Types
Nullable struct
Implicit and explicit nullable conversions
Boxing and unboxing nullable values
Operator Lifting
bool? with & and | Operators
Nullable Types & Null Operators
Scenarios for Nullable Types
Alternatives to Nullable Types
Operator Overloading
Operator Functions
Overloading Equality and Comparison Operators
Custom Implicit and Explicit Conversions
Overloading true and false
Extension Methods
Extension Method Chaining
Ambiguity and Resolution
Anonymous Types
Dynamic Binding
Static Binding Versus Dynamic Binding
Custom Binding
Language Binding
RuntimeBinderException
Runtime Representation of Dynamic
Dynamic Conversions
var Versus dynamic
Dynamic Expressions
Dynamic Calls Without Dynamic Receivers
Static Types in Dynamic Expressions
Uncallable Functions
Attributes
Attribute Classes
Named and Positional Attribute Parameters
Attribute Targets
Specifying Multiple Attributes
Caller Info Attributes (C# 5)
Unsafe Code and Pointers
Pointer Basics
Unsafe Code
The fixed Statement
The Pointer-to-Member Operator
Arrays
void*
Pointers to Unmanaged Code
Preprocessor Directives
Conditional Attributes
Pragma Warning
XML Documentation
Standard XML Documentation Tags
User-Defined Tags
Type or Member Cross-References
Chapter 5. Framework Overview
The CLR and Core Framework
System Types
Text Processing
Collections
Queries
XML
Diagnostics and Code Contracts
Concurrency and Asynchrony
Streams and I/O
Networking
Serialization
Assemblies, Reflection, and Attributes
Dynamic Programming
Security
Advanced Threading
Parallel Programming
Application Domains
Native and COM Interoperability
Applied Technologies
User Interface Technologies
Backend Technologies
Distributed System Technologies
Chapter 6. Framework Fundamentals
String and Text Handling
Char
String
Comparing Strings
StringBuilder
Text Encodings and Unicode
Dates and Times
TimeSpan
DateTime and DateTimeOffset
Dates and Time Zones
DateTime and Time Zones
DateTimeOffset and Time Zones
TimeZone and TimeZoneInfo
Daylight Saving Time and DateTime
Formatting and Parsing
ToString and Parse
Format Providers
Standard Format Strings and Parsing Flags
Numeric Format Strings
NumberStyles
Date/Time Format Strings
DateTimeStyles
Enum Format Strings
Other Conversion Mechanisms
Convert
XmlConvert
Type Converters
BitConverter
Globalization
Globalization Checklist
Testing
Working with Numbers
Conversions
Math
BigInteger
Complex
Random
Enums
Enum Conversions
Enumerating Enum Values
How Enums Work
Tuples
Comparing Tuples
The Guid Struct
Equality Comparison
Value Versus Referential Equality
Standard Equality Protocols
Equality and Custom Types
Order Comparison
IComparable
< and >
Implementing the IComparable Interfaces
Utility Classes
Console
Environment
Process
AppContext
Chapter 7. Collections
Enumeration
IEnumerable and IEnumerator
IEnumerable and IEnumerator
Implementing the Enumeration Interfaces
The ICollection and IList Interfaces
ICollection and ICollection
IList and IList
IReadOnlyList
The Array Class
Construction and Indexing
Enumeration
Length and Rank
Searching
Sorting
Reversing Elements
Copying
Converting and Resizing
Lists, Queues, Stacks, and Sets
List and ArrayList
LinkedList
Queue and Queue
Stack and Stack
BitArray
HashSet and SortedSet
Dictionaries
IDictionary
IDictionary
Dictionary and Hashtable
OrderedDictionary
ListDictionary and HybridDictionary
Sorted Dictionaries
Customizable Collections and Proxies
Collection and CollectionBase
KeyedCollection and DictionaryBase
ReadOnlyCollection
Plugging in Equality and Order
IEqualityComparer and EqualityComparer
IComparer and Comparer
StringComparer
IStructuralEquatable and IStructuralComparable
Chapter 8. LINQ Queries
Getting Started
Fluent Syntax
Chaining Query Operators
Composing Lambda Expressions
Natural Ordering
Other Operators
Query Expressions
Range Variables
Query Syntax Versus SQL Syntax
Query Syntax Versus Fluent Syntax
Mixed-Syntax Queries
Deferred Execution
Reevaluation
Captured Variables
How Deferred Execution Works
Chaining Decorators
How Queries Are Executed
Subqueries
Subqueries and Deferred Execution
Composition Strategies
Progressive Query Building
The into Keyword
Wrapping Queries
Projection Strategies
Object Initializers
Anonymous Types
The let Keyword
Interpreted Queries
How Interpreted Queries Work
Combining Interpreted and Local Queries
AsEnumerable
LINQ to SQL and Entity Framework
LINQ to SQL Entity Classes
Entity Framework Entity Classes
DataContext and ObjectContext
Associations
Deferred Execution with L2S and EF
DataLoadOptions
Eager Loading in Entity Framework
Updates
API Differences Between L2S and EF
Building Query Expressions
Delegates Versus Expression Trees
Expression Trees
Chapter 9. LINQ Operators
Overview
Sequence→Sequence
Sequence→Element or Value
Void→Sequence
Filtering
Where
Take and Skip
TakeWhile and SkipWhile
Distinct
Projecting
Select
SelectMany
Joining
Join and GroupJoin
The Zip Operator
Ordering
OrderBy, OrderByDescending, ThenBy, and ThenByDescending
Grouping
GroupBy
Set Operators
Concat and Union
Intersect and Except
Conversion Methods
OfType and Cast
ToArray, ToList, ToDictionary, and ToLookup
AsEnumerable and AsQueryable
Element Operators
First, Last, and Single
ElementAt
DefaultIfEmpty
Aggregation Methods
Count and LongCount
Min and Max
Sum and Average
Aggregate
Quantifiers
Contains and Any
All and SequenceEqual
Generation Methods
Empty
Range and Repeat
Chapter 10. LINQ to XML
Architectural Overview
What Is a DOM?
The LINQ to XML DOM
X-DOM Overview
Loading and Parsing
Saving and Serializing
Instantiating an X-DOM
Functional Construction
Specifying Content
Automatic Deep Cloning
Navigating and Querying
Child Node Navigation
Parent Navigation
Peer Node Navigation
Attribute Navigation
Updating an X-DOM
Simple Value Updates
Updating Child Nodes and Attributes
Updating Through the Parent
Working with Values
Setting Values
Getting Values
Values and Mixed Content Nodes
Automatic XText Concatenation
Documents and Declarations
XDocument
XML Declarations
Names and Namespaces
Namespaces in XML
Specifying Namespaces in the X-DOM
The X-DOM and Default Namespaces
Prefixes
Annotations
Projecting into an X-DOM
Eliminating Empty Elements
Streaming a Projection
Transforming an X-DOM
Chapter 11. Other XML Technologies
XmlReader
Reading Nodes
Reading Elements
Reading Attributes
Namespaces and Prefixes
XmlWriter
Writing Attributes
Writing Other Node Types
Namespaces and Prefixes
Patterns for Using XmlReader/XmlWriter
Working with Hierarchical Data
Mixing XmlReader/XmlWriter with an X-DOM
XSD and Schema Validation
Performing Schema Validation
XSLT
Chapter 12. Disposal and Garbage Collection
IDisposable, Dispose, and Close
Standard Disposal Semantics
When to Dispose
Opt-in Disposal
Clearing Fields in Disposal
Automatic Garbage Collection
Roots
Garbage Collection and WinRT
Finalizers
Calling Dispose from a Finalizer
Resurrection
How the Garbage Collector Works
Optimization Techniques
Forcing Garbage Collection
Tuning Garbage Collection
Memory Pressure
Managed Memory Leaks
Timers
Diagnosing Memory Leaks
Weak References
Weak References and Caching
Weak References and Events
Chapter 13. Diagnostics and Code Contracts
Conditional Compilation
Conditional Compilation Versus Static Variable Flags
The Conditional Attribute
Debug and Trace Classes
Fail and Assert
TraceListener
Flushing and Closing Listeners
Code Contracts Overview
Why Use Code Contracts?
Contract Principles
Preconditions
Contract.Requires
Contract.Requires
Contract.EndContractBlock
Preconditions and Overridden Methods
Postconditions
Contract.Ensures
Contract.EnsuresOnThrow
Contract.Result and Contract.ValueAtReturn
Contract.OldValue
Postconditions and Overridden Methods
Assertions and Object Invariants
Assertions
Object Invariants
Contracts on Interfaces and Abstract Methods
Dealing with Contract Failure
The ContractFailed Event
Exceptions Within Contract Conditions
Selectively Enforcing Contracts
Contracts in Release Builds
Call-Site Checking
Static Contract Checking
The ContractVerification Attribute
Baselines
The SuppressMessage Attribute
Debugger Integration
Attaching and Breaking
Debugger Attributes
Processes and Process Threads
Examining Running Processes
Examining Threads in a Process
StackTrace and StackFrame
Windows Event Logs
Writing to the Event Log
Reading the Event Log
Monitoring the Event Log
Performance Counters
Enumerating the Available Counters
Reading Performance Counter Data
Creating Counters and Writing Performance Data
The Stopwatch Class
Chapter 14. Concurrency and Asynchrony
Introduction
Threading
Creating a Thread
Join and Sleep
Blocking
Local Versus Shared State
Locking and Thread Safety
Passing Data to a Thread
Exception Handling
Foreground Versus Background Threads
Thread Priority
Signaling
Threading in Rich-Client Applications
Synchronization Contexts
The Thread Pool
Tasks
Starting a Task
Returning values
Exceptions
Continuations
TaskCompletionSource
Task.Delay
Principles of Asynchrony
Synchronous Versus Asynchronous Operations
What is Asynchronous Programming?
Asynchronous Programming and Continuations
Why Language Support Is Important
Asynchronous Functions in C#
Awaiting
Writing Asynchronous Functions
Asynchronous Lambda Expressions
Asynchronous Methods in WinRT
Asynchrony and Synchronization Contexts
Optimizations
Asynchronous Patterns
Cancellation
Progress Reporting
The Task-based Asynchronous Pattern (TAP)
Task Combinators
Obsolete Patterns
Asynchronous Programming Model (APM)
Event-Based Asynchronous Pattern (EAP)
BackgroundWorker
Chapter 15. Streams and I/O
Stream Architecture
Using Streams
Reading and Writing
Seeking
Closing and Flushing
Timeouts
Thread Safety
Backing Store Streams
FileStream
MemoryStream
PipeStream
BufferedStream
Stream Adapters
Text Adapters
Binary Adapters
Closing and Disposing Stream Adapters
Compression Streams
Compressing in Memory
Working with ZIP Files
File and Directory Operations
The File Class
The Directory Class
FileInfo and DirectoryInfo
Path
Special Folders
Querying Volume Information
Catching Filesystem Events
File I/O in Windows Runtime
Working with Directories
Working with Files
Isolated Storage in Windows Store Apps
Memory-Mapped Files
Memory-Mapped Files and Random File I/O
Memory-Mapped Files and Shared Memory
Working with View Accessors
Isolated Storage
Isolation Types
Reading and Writing Isolated Storage
Store Location
Enumerating Isolated Storage
Chapter 16. Networking
Network Architecture
Addresses and Ports
URIs
Client-Side Classes
WebClient
WebRequest and WebResponse
HttpClient
Proxies
Authentication
Exception Handling
Working with HTTP
Headers
Query Strings
Uploading Form Data
Cookies
Forms Authentication
SSL
Writing an HTTP Server
Using FTP
Using DNS
Sending Mail with SmtpClient
Using TCP
Concurrency with TCP
Receiving POP3 Mail with TCP
TCP in Windows Runtime
Chapter 17. Serialization
Serialization Concepts
Serialization Engines
Formatters
Explicit Versus Implicit Serialization
The Data Contract Serializer
DataContractSerializer Versus NetDataContractSerializer
Using the Serializers
Serializing Subclasses
Object References
Version Tolerance
Member Ordering
Null and Empty Values
Data Contracts and Collections
Subclassed Collection Elements
Customizing Collection and Element Names
Extending Data Contracts
Serialization and Deserialization Hooks
Interoperating with [Serializable]
Interoperating with IXmlSerializable
The Binary Serializer
Getting Started
Binary Serialization Attributes
[NonSerialized]
[OnDeserializing] and [OnDeserialized]
[OnSerializing] and [OnSerialized]
[OptionalField] and Versioning
Binary Serialization with ISerializable
Subclassing Serializable Classes
XML Serialization
Getting Started with Attribute-Based Serialization
Subclasses and Child Objects
Serializing Collections
IXmlSerializable
Chapter 18. Assemblies
What’s in an Assembly
The Assembly Manifest
The Application Manifest
Modules
The Assembly Class
Strong Names and Assembly Signing
How to Strongly Name an Assembly
Delay Signing
Assembly Names
Fully Qualified Names
The AssemblyName Class
Assembly Informational and File Versions
Authenticode Signing
How to Sign with Authenticode
Authenticode Validation
The Global Assembly Cache
How to Install Assemblies to the GAC
GAC and Versioning
Resources and Satellite Assemblies
Directly Embedding Resources
.resources Files
.resx Files
Satellite Assemblies
Cultures and Subcultures
Resolving and Loading Assemblies
Assembly and Type Resolution Rules
AssemblyResolve
Loading Assemblies
Deploying Assemblies Outside the Base Folder
Packing a Single-File Executable
Selective Patching
Working with Unreferenced Assemblies
Chapter 19. Reflection and Metadata
Reflecting and Activating Types
Obtaining a Type
Type Names
Base Types and Interfaces
Instantiating Types
Generic Types
Reflecting and Invoking Members
Member Types
C# Members Versus CLR Members
Generic Type Members
Dynamically Invoking a Member
Method Parameters
Using Delegates for Performance
Accessing Nonpublic Members
Generic Methods
Anonymously Calling Members of a Generic Interface
Reflecting Assemblies
Loading an Assembly into a Reflection-Only Context
Modules
Working with Attributes
Attribute Basics
The AttributeUsage Attribute
Defining Your Own Attribute
Retrieving Attributes at Runtime
Retrieving Attributes in the Reflection-Only Context
Dynamic Code Generation
Generating IL with DynamicMethod
The Evaluation Stack
Passing Arguments to a Dynamic Method
Generating Local Variables
Branching
Instantiating Objects and Calling Instance Methods
Exception Handling
Emitting Assemblies and Types
Saving Emitted Assemblies
The Reflection.Emit Object Model
Emitting Type Members
Emitting Methods
Emitting Fields and Properties
Emitting Constructors
Attaching Attributes
Emitting Generic Methods and Types
Defining Generic Methods
Defining Generic Types
Awkward Emission Targets
Uncreated Closed Generics
Circular Dependencies
Parsing IL
Writing a Disassembler
Chapter 20. Dynamic Programming
The Dynamic Language Runtime
Numeric Type Unification
Dynamic Member Overload Resolution
Simplifying the Visitor Pattern
Anonymously Calling Members of a Generic Type
Implementing Dynamic Objects
DynamicObject
ExpandoObject
Interoperating with Dynamic Languages
Passing State Between C# and a Script
Chapter 21. Security
Permissions
CodeAccessPermission and PrincipalPermission
PermissionSet
Declarative Versus Imperative Security
Code Access Security (CAS)
How Code Access Security Is Applied
Testing for Full Trust
Allowing Partially Trusted Callers
Elevation of Privilege
APTCA and [SecurityTransparent]
The Transparency Model
How the Transparency Model Works
How to Write APTCA Libraries with Transparency
Transparency in Full-Trust Scenarios
Sandboxing Another Assembly
Asserting Permissions
Operating System Security
Running in a Standard User Account
Administrative Elevation and Virtualization
Identity and Role Security
Assigning Users and Roles
Cryptography Overview
Windows Data Protection
Hashing
Symmetric Encryption
Encrypting in Memory
Chaining Encryption Streams
Disposing Encryption Objects
Key Management
Public Key Encryption and Signing
The RSA Class
Digital Signing
Chapter 22. Advanced Threading
Synchronization Overview
Exclusive Locking
The lock Statement
Monitor.Enter and Monitor.Exit
Choosing the Synchronization Object
When to Lock
Locking and Atomicity
Nested Locking
Deadlocks
Performance
Mutex
Locking and Thread Safety
Thread Safety and .NET Framework Types
Thread Safety in Application Servers
Immutable Objects
Nonexclusive Locking
Semaphore
Reader/Writer Locks
Signaling with Event Wait Handles
AutoResetEvent
ManualResetEvent
CountdownEvent
Creating a Cross-Process EventWaitHandle
Wait Handles and Continuations
Converting Wait Handles to Tasks
WaitAny, WaitAll, and SignalAndWait
The Barrier Class
Lazy Initialization
Lazy
LazyInitializer
Thread-Local Storage
[ThreadStatic]
ThreadLocal
GetData and SetData
Interrupt and Abort
Suspend and Resume
Timers
Multithreaded Timers
Single-Threaded Timers
Chapter 23. Parallel Programming
Why PFX?
PFX Concepts
PFX Components
When to Use PFX
PLINQ
Parallel Execution Ballistics
PLINQ and Ordering
PLINQ Limitations
Example: Parallel Spellchecker
Functional Purity
Setting the Degree of Parallelism
Cancellation
Optimizing PLINQ
The Parallel Class
Parallel.Invoke
Parallel.For and Parallel.ForEach
Task Parallelism
Creating and Starting Tasks
Waiting on Multiple Tasks
Canceling Tasks
Continuations
Task Schedulers
TaskFactory
Working with AggregateException
Flatten and Handle
Concurrent Collections
IProducerConsumerCollection
ConcurrentBag
BlockingCollection
Writing a Producer/Consumer Queue
Chapter 24. Application Domains
Application Domain Architecture
Creating and Destroying Application Domains
Using Multiple Application Domains
Using DoCallBack
Monitoring Application Domains
Domains and Threads
Sharing Data Between Domains
Sharing Data via Slots
Intra-Process Remoting
Isolating Types and Assemblies
Chapter 25. Interoperability
Calling into Native DLLs
Type Marshaling
Marshaling Common Types
Marshaling Classes and Structs
In and Out Marshaling
Callbacks from Unmanaged Code
Simulating a C Union
Shared Memory
Mapping a Struct to Unmanaged Memory
fixed and fixed {...}
COM Interoperability
The Purpose of COM
The Basics of the COM Type System
Calling a COM Component from C#
Optional Parameters and Named Arguments
Implicit ref Parameters
Indexers
Dynamic Binding
Embedding Interop Types
Type Equivalence
Primary Interop Assemblies
Exposing C# Objects to COM
Chapter 26. Regular Expressions
Regular Expression Basics
Compiled Regular Expressions
RegexOptions
Character Escapes
Character Sets
Quantifiers
Greedy Versus Lazy Quantifiers
Zero-Width Assertions
Lookahead and Lookbehind
Anchors
Word Boundaries
Groups
Named Groups
Replacing and Splitting Text
MatchEvaluator Delegate
Splitting Text
Cookbook Regular Expressions
Recipes
Regular Expressions Language Reference
Chapter 27. The Roslyn Compiler
Roslyn Architecture
Workspaces
Syntax Trees
SyntaxTree Structure
Obtaining a Syntax Tree
Traversing and Searching a Tree
Trivia
Transforming a Syntax Tree
Compilations and Semantic Models
Creating a Compilation
Emitting an Assembly
Querying the Semantic Model
Example: Renaming a Symbol
Index
th v 6th E C o e R ers .N o sly n C o E n ditio T 4.6 & piler m C# 6.0 in a Nutshell THE DEFINITIVE REFERENCE Joseph Albahari & Ben Albahari www.it-ebooks.info
C# 6.0 in a Nutshell When you have questions about C# 6.0 or the .NET CLR and its core Framework assemblies, this bestselling guide has the answers you need. C# has become a language of unusual flexibility and breadth since its premiere in 2000, but this continual growth means there’s still much more to learn. Organized around concepts and use cases, this thoroughly updated sixth edition provides intermediate and advanced programmers with a concise map of C# and .NET knowledge. Dive in and discover why this Nutshell guide is considered the definitive reference on C#. ■ Get up to speed with all aspects of the C# language, from the basics of syntax and variables, to advanced topics such as pointers and operator overloading ■ Dig deep into LINQ via three chapters dedicated to the topic ■ Learn about dynamic, asynchronous, and parallel programming ■ Work with .NET features, including XML, networking, serialization, reflection, security, application domains, and code contracts ■ Explore the new C# 6.0 compiler-as-a- service, Roslyn “ C# 6.0 in a Nutshell is one of the few books I keep on my desk as a quick reference.” —Scott Guthrie Microsoft “ Novices and experts alike will find the latest techniques in C# programming here.” —Eric Lippert C# MVP Joseph Albahari, author of C# 5.0 in a Nutshell, C# 5.0 Pocket Reference, and LINQ Pocket Reference, also wrote LINQPad, the popular code scratchpad and LINQ querying utility.. Ben Albahari, a former program manager at Microsoft, is cofounder of Auditionist, a casting website for actors in the UK. C#/MICROSOFT .NET US $59.99 CAN $68.99 ISBN: 978-1-491-92706-9 Twitter: @oreillymedia facebook.com/oreilly www.it-ebooks.info
C# 6.0 IN A NUTSHELL Joseph Albahari & Ben Albahari www.it-ebooks.info
C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari Copyright © 2016 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://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest Editor: Brian MacDonald Production Editor: Kristen Brown Proofreader: Amanda Kersey Indexer: Angela Howard December 2015: Sixth Edition Revision History for the Sixth Edition 2015-11-03: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491927069 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. C# 6.0 in a Nutshell, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the informa‐ tion and instructions contained in this work are accurate, the publisher and the authors dis‐ claim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technol‐ ogy this work contains or describes is subject to open source licenses or the intellectual prop‐ erty rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-92706-9 [M] www.it-ebooks.info
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. 1 Introducing C# and the .NET Framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object Orientation 1 Type Safety 2 Memory Management 3 Platform Support 3 C#’s Relationship with the CLR 3 The CLR and .NET Framework 3 C# and Windows Runtime 5 What’s New in C# 6.0 6 What Was New in C# 5.0 8 What Was New in C# 4.0 8 What Was New in C# 3.0 9 2. C# Language Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 A First C# Program 11 Syntax 14 Type Basics 17 Numeric Types 26 Boolean Type and Operators 33 Strings and Characters 35 Arrays 38 Variables and Parameters 42 Expressions and Operators 51 Null Operators 55 Statements 56 Namespaces 65 3. Creating Types in C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 www.it-ebooks.info iii
Classes 73 Inheritance 88 The object Type 97 Structs 101 Access Modifiers 102 Interfaces 104 Enums 109 Nested Types 113 Generics 114 4. Advanced C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Delegates 127 Events 136 Lambda Expressions 143 Anonymous Methods 147 try Statements and Exceptions 148 Enumeration and Iterators 156 Nullable Types 162 Operator Overloading 168 Extension Methods 171 Anonymous Types 174 Dynamic Binding 175 Attributes 183 Caller Info Attributes (C# 5) 185 Unsafe Code and Pointers 187 Preprocessor Directives 190 XML Documentation 193 5. Framework Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 The CLR and Core Framework 202 Applied Technologies 206 6. Framework Fundamentals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 String and Text Handling 213 Dates and Times 226 Dates and Time Zones 234 Formatting and Parsing 240 Standard Format Strings and Parsing Flags 246 Other Conversion Mechanisms 253 Globalization 257 Working with Numbers 258 Enums 262 iv | Table of Contents www.it-ebooks.info
Tuples 266 The Guid Struct 267 Equality Comparison 267 Order Comparison 278 Utility Classes 281 7. Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Enumeration 285 The ICollection and IList Interfaces 293 The Array Class 297 Lists, Queues, Stacks, and Sets 305 Dictionaries 314 Customizable Collections and Proxies 321 Plugging in Equality and Order 327 8. LINQ Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Getting Started 335 Fluent Syntax 337 Query Expressions 344 Deferred Execution 348 Subqueries 355 Composition Strategies 358 Projection Strategies 362 Interpreted Queries 364 LINQ to SQL and Entity Framework 371 Building Query Expressions 385 9. LINQ Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 Overview 393 Filtering 396 Projecting 400 Joining 412 Ordering 420 Grouping 423 Set Operators 426 Conversion Methods 427 Element Operators 430 Aggregation Methods 432 Quantifiers 437 Generation Methods 438 10. LINQ to XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 Table of Contents | v www.it-ebooks.info
Architectural Overview 441 X-DOM Overview 442 Instantiating an X-DOM 446 Navigating and Querying 448 Updating an X-DOM 453 Working with Values 456 Documents and Declarations 459 Names and Namespaces 463 Annotations 468 Projecting into an X-DOM 469 11. Other XML Technologies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 XmlReader 478 XmlWriter 487 Patterns for Using XmlReader/XmlWriter 489 XSD and Schema Validation 493 XSLT 496 12. Disposal and Garbage Collection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 IDisposable, Dispose, and Close 499 Automatic Garbage Collection 505 Finalizers 507 How the Garbage Collector Works 512 Managed Memory Leaks 516 Weak References 520 13. Diagnostics and Code Contracts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525 Conditional Compilation 525 Debug and Trace Classes 529 Code Contracts Overview 532 Preconditions 537 Postconditions 541 Assertions and Object Invariants 543 Contracts on Interfaces and Abstract Methods 545 Dealing with Contract Failure 546 Selectively Enforcing Contracts 548 Static Contract Checking 549 Debugger Integration 551 Processes and Process Threads 552 StackTrace and StackFrame 553 Windows Event Logs 555 Performance Counters 557 vi | Table of Contents www.it-ebooks.info
分享到:
收藏