1. Trang chủ
  2. » Công Nghệ Thông Tin

Apress - Accelerated C#_10 pdf

8 306 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Home Page

  • Prelim

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewer

  • Acknowledgments

  • Preface

    • About This Book

  • C# Preview

    • Differences Between C# and C++

      • C#

      • C++

      • CLR Garbage Collection

    • Example of a C# Program

    • Overview of Features Added in C# 2.0

    • Overview of Features Added in C# 3.0

    • Overview of New C# 4.0 Features

    • Summary

  • C# and the CLR

    • The JIT Compiler in the CLR

    • Assemblies and the Assembly Loader

      • Minimizing the Working Set of the Application

      • Naming Assemblies

      • Loading Assemblies

    • Metadata

    • Cross-Language Compatibility

    • Summary

  • C# Syntax Overview

    • C# Is a Strongly Typed Language

    • Expressions

    • Statements and Expressions

    • Types and Variables

      • Value Types

      • Enumerations

      • Flags Enumerations

      • Reference Types

      • Default Variable Initialization

      • Implicitly Typed Local Variables

      • Type Conversion

      • Array Covariance

      • Boxing Conversion

      • as and is Operators

      • Generics

    • Namespaces

      • Defining Namespaces

      • Using Namespaces

    • Control Flow

      • if-else, while, do-while, and for

      • switch

      • foreach

      • break, continue, goto, return, and throw

    • Summary

  • Classes, Structs, and Objects

    • Class Definitions

      • Fields

      • Constructors

      • Methods

      • Static Methods

      • Instance Methods

      • Properties

      • Declaring Properties

      • Accessors

      • Read-Only and Write-Only Properties

      • Auto-Implemented Properties

      • Encapsulation

      • Accessibility

      • Interfaces

      • Inheritance

      • Accessibility of Members

      • Implicit Conversion and a Taste of Polymorphism

      • Member Hiding

      • The base Keyword

      • sealed Classes

      • abstract Classes

      • Nested Classes

      • Indexers

      • partial Classes

      • partial Methods

      • Static Classes

      • Reserved Member Names

      • Reserved Names for Properties

      • Reserved Names for Indexers

      • Reserved Names for Destructors

      • Reserved Names for Events

    • Value Type Definitions

      • Constructors

      • The Meaning of this

      • Finalizers

      • Interfaces

    • Anonymous Types

    • Object Initializers

    • Boxing and Unboxing

      • When Boxing Occurs

      • Efficiency and Confusion

    • System.Object

      • Equality and What It Means

      • The IComparable Interface

    • Creating Objects

      • The new Keyword

      • Using new with Value Types

      • Using new with Class Types

      • Field Initialization

      • Static (Class) Constructors

      • Instance Constructor and Creation Ordering

    • Destroying Objects

      • Finalizers

      • Deterministic Destruction

      • Exception Handling

    • Disposable Objects

      • The IDisposable Interface

      • The using Keyword

    • Method Parameter Types

      • Value Arguments

      • ref Arguments

      • out Parameters

      • param Arrays

      • Method Overloading

      • Optional Arguments

      • Named Arguments

    • Inheritance and Virtual Methods

      • Virtual and Abstract Methods

      • override and new Methods

      • sealed Methods

      • A Final Few Words on C# Virtual Methods

    • Inheritance, Containment, and Delegation

      • Choosing Between Interface and Class Inheritance

      • Delegation and Composition vs. Inheritance

    • Summary

  • Interfaces and Contracts

    • Interfaces Define Types

    • Defining Interfaces

      • What Can Be in an Interface?

      • Interface Inheritance and Member Hiding

    • Implementing Interfaces

      • Implicit Interface Implementation

      • Explicit Interface Implementation

      • Overriding Interface Implementations in Derived Classes

      • Beware of Side Effects of Value Types Implementing Interfaces

    • Interface Member Matching Rules

    • Explicit Interface Implementation with Value Types

    • Versioning Considerations

    • Contracts

      • Contracts Implemented with Classes

      • Interface Contracts

    • Choosing Between Interfaces and Classes

    • Summary

  • Overloading Operators

    • Just Because You Can Doesn’t Mean You Should

    • Types and Formats of Overloaded Operators

    • Operators Shouldn’t Mutate Their Operands

    • Does Parameter Order Matter?

    • Overloading the Addition Operator

    • Operators That Can Be Overloaded

      • Comparison Operators

      • Conversion Operators

      • Boolean Operators

    • Summary

  • Exception Handling and Exception Safety

    • How the CLR Treats Exceptions

    • Mechanics of Handling Exceptions in C#

      • Throwing Exceptions

      • Changes with Unhandled Exceptions Starting with .NET 2.0

      • Syntax Overview of the try, catch, and finally Statements

      • Rethrowing Exceptions and Translating Exceptions

      • Exceptions Thrown in finally Blocks

      • Exceptions Thrown in Finalizers

      • Exceptions Thrown in Static Constructors

    • Who Should Handle Exceptions?

    • Avoid Using Exceptions to Control Flow

    • Achieving Exception Neutrality

      • Basic Structure of Exception-Neutral Code

      • Constrained Execution Regions

      • Critical Finalizers and SafeHandle

    • Creating Custom Exception Classes

    • Working with Allocated Resources and Exceptions

    • Providing Rollback Behavior

    • Summary

  • Working with Strings

    • String Overview

    • String Literals

    • Format Specifiers and Globalization

      • Object.ToString, IFormattable, and CultureInfo

      • Creating and Registering Custom CultureInfo Types

      • Format Strings

      • Console.WriteLine and String.Format

      • Examples of String Formatting in Custom Types

      • ICustomFormatter

      • Comparing Strings

    • Working with Strings from Outside Sources

    • StringBuilder

    • Searching Strings with Regular Expressions

      • Searching with Regular Expressions

      • Searching and Grouping

      • Replacing Text with Regex

      • Regex Creation Options

    • Summary

  • Arrays, Collection Types, and Iterators

    • Introduction to Arrays

      • Implicitly Typed Arrays

      • Type Convertibility and Covariance

      • Sortability and Searchability

      • Synchronization

      • Vectors vs. Arrays

    • Multidimensional Rectangular Arrays

    • Multidimensional Jagged Arrays

    • Collection Types

      • Comparing ICollection<T> with ICollection

      • Collection Synchronization

      • Lists

      • Dictionaries

      • Sets

      • System.Collections.ObjectModel

      • Efficiency

    • IEnumerable<T>, IEnumerator<T>, IEnumerable, and IEnumerator

      • Types That Produce Collections

    • Iterators

      • Forward, Reverse, and Bidirectional Iterators

    • Collection Initializers

    • Summary

  • Delegates, Anonymous Functions, and Events

    • Overview of Delegates

    • Delegate Creation and Use

      • Single Delegate

      • Delegate Chaining

      • Iterating Through Delegate Chains

      • Unbound (Open Instance) Delegates

    • Events

    • Anonymous Methods

      • Captured Variables and Closures

      • Beware the Captured Variable Surprise

      • Anonymous Methods as Delegate Parameter Binders

    • The Strategy Pattern

    • Summary

  • Generics

    • Difference Between Generics and C++ Templates

    • Efficiency and Type Safety of Generics

    • Generic Type Definitions and Constructed Types

      • Generic Classes and Structs

      • Generic Interfaces

      • Generic Methods

      • Generic Delegates

      • Generic Type Conversion

      • Default Value Expression

      • Nullable Types

      • Constructed Types Control Accessibility

      • Generics and Inheritance

    • Constraints

      • Constraints on Nonclass Types

    • Coand Contravariance

      • Covariance

      • Contravariance

      • Invariance

      • Variance and Delegates

    • Generic System Collections

    • Generic System Interfaces

    • Select Problems and Solutions

      • Conversion and Operators within Generic Types

      • Creating Constructed Types Dynamically

    • Summary

  • Threading in C#

    • Threading in C# and .NET

      • Starting Threads

      • Passing Data to New Threads

      • Using ParameterizedThreadStart

      • The IOU Pattern and Asynchronous Method Calls

      • States of a Thread

      • Terminating Threads

      • Halting Threads and Waking Sleeping Threads

      • Waiting for a Thread to Exit

      • Foreground and Background Threads

      • Thread-Local Storage

      • How Unmanaged Threads and COM Apartments Fit In

    • Synchronizing Work Between Threads

      • Lightweight Synchronization with the Interlocked Class

      • SpinLock Class

      • Monitor Class

      • Beware of Boxing

      • Pulse and Wait

      • Locking Objects

      • ReaderWriterLock

      • ReaderWriterLockSlim

      • Mutex

      • Semaphore

      • Events

      • Win32 Synchronization Objects and WaitHandle

    • Using ThreadPool

      • Asynchronous Method Calls

      • Timers

    • Concurrent Programming

      • Task Class

      • Parallel Class

      • Easy Entry to the Thread Pool

    • Thread-Safe Collection Classes

    • Summary

  • In Search of C# Canonical Forms

    • Reference Type Canonical Forms

      • Default to sealed Classes

      • Use the Non-Virtual Interface (NVI) Pattern

      • Is the Object Cloneable?

      • Is the Object Disposable?

      • Does the Object Need a Finalizer?

      • What Does Equality Mean for This Object?

      • Reference Types and Identity Equality

      • Value Equality

      • Overriding Object.Equals for Reference Types

      • If You Override Equals, Override GetHashCode Too

      • Does the Object Support Ordering?

      • Is the Object Formattable?

      • Is the Object Convertible?

      • Prefer Type Safety at All Times

      • Using Immutable Reference Types

    • Value Type Canonical Forms

      • Override Equals for Better Performance

      • Do Values of This Type Support Any Interfaces?

      • Implement Type-Safe Forms of Interface Members and Derived Methods

    • Summary

      • Checklist for Reference Types

      • Checklist for Value Types

  • Extension Methods

    • Introduction to Extension Methods

      • How Does the Compiler Find Extension Methods?

      • Under the Covers

      • Code Readability versus Code Understandability

    • Recommendations for Use

      • Consider Extension Methods Over Inheritance

      • Isolate Extension Methods in Separate Namespace

      • Changing a Type’s Contract Can Break Extension Methods

    • Transforms

    • Operation Chaining

    • Custom Iterators

      • Borrowing from Functional Programming

    • The Visitor Pattern

    • Summary

  • Lambda Expressions

    • Introduction to Lambda Expressions

      • Lambda Expressions and Closures

      • Closures in C# 1.0

      • Closures in C# 2.0

      • Lambda Statements

    • Expression Trees

      • Operating on Expressions

      • Functions as Data

    • Useful Applications of Lambda Expressions

      • Iterators and Generators Revisited

      • More on Closures (Variable Capture) and Memoization

      • Currying

      • Anonymous Recursion

    • Summary

  • LINQ: Language Integrated Query

    • A Bridge to Data

      • Query Expressions

      • Extension Methods and Lambda Expressions Revisited

    • Standard Query Operators

    • C# Query Keywords

      • The from Clause and Range Variables

      • The join Clause

      • The where Clause and Filters

      • The orderby Clause

      • The select Clause and Projection

      • The let Clause

      • The group Clause

      • The into Clause and Continuations

    • The Virtues of Being Lazy

      • C# Iterators Foster Laziness

      • Subverting Laziness

      • Executing Queries Immediately

      • Expression Trees Revisited

    • Techniques from Functional Programming

      • Custom Standard Query Operators and Lazy Evaluation

      • Replacing foreach Statements

    • Summary

  • Dynamic Types

    • What does dynamic Mean?

    • How Does dynamic Work?

      • The Great Unification

      • Call Sites

      • Objects with Custom Dynamic Behavior

      • Efficiency

      • Boxing with Dynamic

    • Dynamic Conversions

      • Implicit Dynamic Expressions Conversion

    • Dynamic Overload Resolution

    • Dynamic Inheritance

      • You Cannot Derive from dynamic

      • You Cannot Implement dynamic Interfaces

      • You Can Derive From Dynamic Base Types

    • Duck Typing in C#

    • Limitations of dynamic Types

    • ExpandoObject: Creating Objects Dynamically

    • Summary

  • Index

    • Symbols

    • A

    • B

    • C

    • D

    • E

    • F

    • G

    • H

    • I

    • J

    • K

    • L

    • M

    • N

    • O

    • P

    • Q

    • R

    • S

    • T

    • V

    • U

    • W

    • X

    • Y

Nội dung

■ INDEX 620 partial, 77–79 sealed, 131 static, 49–50 virtual, 67–69, 128–132 Microsoft Foundation Classes (MFC), 149 Microsoft Windows Internals, Fourth Edition: Microsoft Windows Server 2003, Windows XP, and Windows 2000 (Russinovich & Solomon), 401 Min method, 566 mirror overload, 168 Modern C++ Design: Generic Programming and Design Patterns Applied (Alexandrescu), 325 Monitor class, 249, 378, 387–396, 401–402 Monitor.Enter method, 390, 393 Monitor.Exit method, 390, 393 Monitor.Pulse method, 393, 396 Monitor.Wait method, 368, 393 Mono project, 2 MoveNext method, 267, 269 mscorlib assembly, 4 MTAThreadAttribute attribute, 377 MulticastDelegate class, 280 multidimensional arrays, 251–255 multiple assemblies, 12 multiple inheritance, 132 MultiplyBy2 method, 294 MultiplyBy4 method, 294 multithreaded apartment (MTA), 377 multithreading. See threading mutating operands, avoiding, 167 Mutex class, 378 vs. Monitor class, 388 Mutex objects, 401, 402 MyClass< Stack<T> >, 311 MyClass<int>, 313 MyClass<T>, 312 MyCollection<int>, 307 MyCollection<long>, 307, 316 MyCollection<T>, 307 MyContainer<int>, 316 MyContainer<T>, 316, 322 MyNestedClass<T>, 313 ■ N name conflicts, 81 named arguments, 7, 125–128 namespace aliasing, 38 namespaces, 4, 35–38 coding practices, 496–497 declaring, 36–37 global, 37 importing, 490 side effects, avoiding, 496 using, 37–38, 490 naming conventions for culture names, 219 for exceptions, 206 for interfaces, 139, 157 for methods, 138 generic type parameter placeholders and, 311 namespaces and, 36 Nathan, Adam, 9 native applications, 2, 11 native code, 2 nested classes, 71–74 .NET exception handling and, 116 threading and, 361–378 .NET 2.0 catch clauses and, 185 unhandled exceptions in, 182–183 .NET and COM: The Complete Interoperability Guide (Nathan), 9 The .NET Developer’s Guide to Windows Security (Brown), 9 .NET Framework Security (LaMacchia), 9, 272 new constraints, 330–331 new keyword, 74, 84, 139 class types and, 103–104 member hiding and, 67, 74, 141, 149 method overrides and, 129–131 uses, 103 value types and, 103 new operator, 27, 317 nondeterministic destruction, 115 nondeterministic finalization, 118 NonGeneric method, 311 nongeneric types, 311 non-nested classes, 71 Non-Virtual Interface (NVI) pattern, 431–434 NotSupportedException, 262, 269 null values, 323–324 nullable types, 323–324 Nullable<T>, 323–324 NullReferenceException, 182, 192, 291 NVI pattern, 431–434 ■ O Object class, 101–103, 154, 243 object initializers, 6 nesting, 92 ■ INDEX 621 syntax, 91–94 uses, 91 object keyword, 101 object references, 44 object type, 22 Object.Equals method, 103, 450–457 Object.ToString method, 218, 221, 225 ObjectDisposedException, 441 Object-Oriented Analysis/Design (OOA/D), 141 object-oriented methodologies, 25 object-oriented programming, 544 objects, 43 copies and, 434–440 C# vs. C++, 27, 430 creating, 103–113, 430 destroying, 44, 113–116 disposable, 116–119 internal state of, 43 memory allocation for, 113 memory associated with, 44 terminology and, 26 On<event> method, 291 OOA/D (Object-Oriented Analysis/Design), 141 open instance delegates, 285–288 open types. See generic types operands, 167 operation chaining, 502–503 operator overloading, 18, 165–179 addition operator, 168–169 Boolean operators, 176–179 mutating operands and, 167 operators for, 169–179 parameter order and, 167–168 reasons not to use, 165 semantics and, 165 types and formats, 165–166 Visual Basic and, 457 operator precedence, 18–20 operators applying to parameterized types, 347–357 declaring, C# vs. C++, 166 optimizations, 11 optional arguments, 124–125 orderby clause (LINQ), 553–554, 563–565 ordering of object instance creation, 109–113 Ordinal property, 228 OrdinalIgnoreCase property, 228 OS threads, 361 out keyword, 122, 337 out parameters, 85, 122–123 OutOfMemoryException, 199–201 overflow errors, 174 overload resolution, 592 dynamic, 592–594 overloadable operators. See operator overloading overloaded constructors, 49 overloading methods, 123, 126 override keyword, 129 ■ P P/Invoke, 201–205 Parallel class, 420–425 Parallel Extensions, 417–418 Parallel.For method, 422 Parallel.Invoke, 425–426 param arrays, 123 param parameters, 123 parameter binding, 300–303, 538 ParameterExpression, 527 ParameterizedThreadStart delegate, 365 parameters order, 167–168 out, 122–123 params keyword, 123 parentheses, 235 partial classes, 76–77 partial keyword, 77 partial methods described, 77–79 restrictions, 77 uses, 6, 78 partial types, 6 partially named assemblies, 12 PassAsOutParam() method, 123 PassByRef() method, 121 PassByValue() method, 121 patterns, design, 137 PE (Portable Executable) file format, 2 performance, collection types and, 262–263 phantom method, 594 PlayEvent identifier, 291 polymorphism, 44, 63–65, 129 Portable Executable (PE) file format, 2 positional arguments, 126 postfix operator (++), 167 prefix operator ( ), 167 PrepareConstrainedRegions method, 199 primary constraints, 330 Primary Interop Assemblies (PIA), 578 printf method, vs. String.Format method, 222 Priority property, 363 private access modifier, 60 private assemblies, 13 private field modifier, 46 ■ INDEX 622 private virtual methods, C++ and, 433 Pro C# 2005 and the .NET 2.0 Platform, Third Edition (Troelsen), 9 ProcessResults type, 282 profile-guided optimizations, 11 projection operators, 546 projector clause (LINQ). See group clause (LINQ); select clause (LINQ) properties accessors and, 53 auto-implemented. See auto-implemented properties declaring, 51 public, 52 read-only, 47, 53 reserved names and, 81 uses, 51 write-only, 53 protected access modifier, 60 protected field modifier, 46 protected internal access modifier, 60 protected virtual methods, 291 public access modifier, 60 public field modifier, 46 publish/subscribe, 289 Pulse method, 393, 396 ■ Q query expressions, 544–546 keywords, 549–550 query variables (LINQ), 546, 562, 563, 564 Queryable class, 565 Queryable.Where method, 553 Queue.Clear method, 256 Queue<T> class, 344 QueueProcessor class, 364 QueueUserWorkItem method, 408 ■ R R identifier, 312, 314 RAII (Resource Acquisition Is Initialization), 115, 207, 430 range checking, 244 Range method, 565 range variables (LINQ), 546, 549–550, 562–565 rank, of arrays, 248, 253 RankException, 248 Rattz, Joseph C., Jr., 576 read thread mode, 400 ReaderWriterLock, 397–401 ReaderWriterLockSlim, 400–401 readonly field modifier, 47 readonly fields, 48 readonly properties, 47, 53 readonly public field, 53 rectangular arrays, 251–253 recursion, anonymous, 540–541 recursive computations, 421 ref arguments, 120–122 ref keyword, 121 ref parameters, 121–123 reference type variables, 22–23, 27, 44 reference types, 3, 22–23, 26–27, 44 canonical forms and, 429–476 checklist for, 429, 485–486 convertability and, 247–248 default values, 27 described, 94 explicit interface implementation and, 154 identity equality and, 451–453 immutability and, 473, 476 overriding Object.Equals method for, 454– 457 sealed classes and, 430–431 type conversion, 30 type safety and, 469–473 referenced assemblies, 14 ReferenceEquals method, 456 referential equality, 456 reflection, 14, 270, 272 Regex class, 232–242 Regex.Replace method, 238 RegexOptions, 240–242 RegionInfo types, 219 Register method, 220 regular expressions searching strings with, 232–242 text substitution and, 238–240 regular-expression substitutions, 239 Release method, 402 ReleaseHandle method, 205 ReleaseMutex method, 401 ReleaseReaderLock method, 398 ReliabilityContractAttribute (ListSwap method), 201 Remove method, 283, 292 RemoveAll method, 283 Repeat method, 565 Replace method, 234, 240 reserved member names, 59, 81–82 Reset method, 267–269 ResetAbort method, 368–370 Resource Acquisition Is Initialization (RAII), 115, 207, 430 ■ INDEX 623 resources for further reading assembly loading, 13 C++ design, 325 CLR, 9 code access security, 272 efficiency bottlenecks, 262 exception handling, 193 exception-neutral code, 196 hash codes, generating, 459 interface tables, 152 interface-based programming, 137 libraries, 70 metadata, 15 method tables, 129 regular expressions, 232 types, 273 Resume method, 372, 379 rethrowing exceptions, 186–187 return statement, 40–41 reverse iterators, 273–277 Reverse method, 566 RndThreadFunc method, 381, 385 rollback behavior, 211–214 rude thread abort, 369 Running state, of threads, 368, 377 Runtime Callable Wrapper (RCW), 578 RuntimeCompatibilityAttribute, 185 RuntimeHelpers class, 199 RuntimeWrappedException, 185 Russinovich, Mark E., 401 ■ S safe code, 27 safe points, 372 SafeHandle class, 114, 201–205, 407 SafeWaitHandle class, 407 sample code complex numbers and, 247–357, 462 employee raises, delegates and, 286 media player, events and, 288–292 sbyte type, 21, 24 sealed classes, 69, 145, 430–431, 495 sealed keyword, 70, 131, 430 sealed methods, 131 searchability, 248 select clause (LINQ), 552–555, 563–564 Sells, Chris, 9, 129 semantics, operator overloading and, 165 SemaphoreFullExceptions, 402 semaphores, 402 semicolon, 20 Serializable attribute, 45 SerializableAttribute, 206 set accessor, 53 Set method, multidimensional array and, 253 SetMinThreads method, 408 sets. See HashSet collection class SetValue method, multidimensional array and, 253 shallow copies, objects and, 435, 440 short type, 21, 24 Shutdown method, 396 single inheritance, 133 single-threaded apartment (STA), 377 Singleton design pattern, 159 Singleton pattern, 80, 314 Skip method (LINQ), 562 SkipWhile method (LINQ), 562 Sleep method, 368, 371, 379, 383 SMP (symmetric multiprocessing), 381 SOA (service-oriented architecture) systems, 137 Socket class, 413 Solomon, David A., 401 SomeFunction() method, 50 SomeMethod() method, 130 SomeOperation() method, 51 sortability, 248 SortedDictionary<TKey, TValue> class, 259, 344 SortedList<T> class, 344 SortedList<TKey, TValue> class, 344 sorting, 554 SortStrategy delegate, 305 specialization, 63 spin locks, 382 SpinLock class, 385–387 SpinLock.Enter method, 384 SpinLockManager, 385 SQL, 544–545 Stack.Clear method, 256 Stack<T> class, 344 StackOverflowException, 198–199 standard query operators, 544, 547–548 Start method, 368 StartsWith method, 232 statements, 20 STAThreadAttribute attribute, 377 static classes, 79–80 static constructors, 49, 106–109, 314 exceptions thrown in, 191–192 static field modifier, 46 static fields, 46 static methods, 49–50 static modifier, 79 static receiver, 582 ■ INDEX 624 StaticCompute method, 284 STL (Standard Template Library) programming, 300, 502, 529, 538, 576 Stop method, 277 Strategy pattern, 292, 304–305 Strategy property, 294 streams. See iterators, over infinite sets StreamWriter, 384 String class, 215, 227, 229, 438 string literals, 216–217 string type, 22 String.Compare method, 227 String.Copy method, 438 String.Format method, 222–224 String.Intern method, 217 String.Join method, 575 StringBuilder class, 230–232 StringBuilder.AppendFormat method, 224 StringComparer class, 227 StringComparer.Create method, 228 StringComparison enumeration, 227 strings, 215 comparing, 227– 228 converting, 467 floating-point values, converting to, 219 format, 465 format specifiers and, 217–228, 465 format, 221–227 memory issues, 230 outside sources and, 228–230 overview, 215, 216 searching with regular expressions, 232–242 verbatim, 217 strong typing. See also variables, implicitly typed local strongly named assemblies, 12–13 strongly typed languages, 17–18, 469 struct constraints, 330–331 struct declarations, 21 struct keyword, 22–23, 44, 82 struct member definitions, access modifiers, 60 structs contents, 82 generic, 311–314 interfaces and, 87 SubmitWorkItem method, 396 Sum method, 566 SuppressFinalize() method, 118, 446 Suspend method, 369, 372, 379 Suspended state, of threads, 369 SuspendRequested state, of threads, 369 Sutter, Herb, 196 swap operations, 198 switch statement, 39 symmetric multiprocessing (SMP), 381 sync events, 404 synchronization, 249 collections and, 257 enumerators, 269 Interlocked class and, 379–385 locking objects and, 396–402 Monitor class and, 387–396 semaphores and, 402–404 SpinLock class and, 385–387 threading and, 378–407 WaitHandle and, 405–407 synchronized field, 270 Synchronized method, 257 SyncRoot property, 257, 267 syntax, 17–41 sysglobl.dll assembly, 220 system heap, 44 System namespace, 21, 35 System Performance Monitor (perfmon), 423 System.Activator namespace, 358 System.Array, 243, 253 vectors and, 250 System.Array interface, 248 System.Collections namespace, 255, 310 System.Collections.Concurrent namespace, 421 System.Collections.Generic namespace, 255, 344–345 System.Collections.ObjectModel namespace, 255–256, 260–262 System.Collections.Specialized namespace, 255 System.Console class, 80 System.Convert class, 231 System.Double namespace, 221 System.Dynamic.DynamicObject, 585 System.Exception exception, 185, 188, 206–207 System.Globalization namespace, 219 System.Int32, 150 System.Int32.MaxValue, 231 System.Ling namespace, 545 System.Ling.Enumerable class, 544, 566 System.Ling.Expressions namespace, 518, 524, 528 System.Ling.Expressions.Expression<>, 524 System.Ling.Queryable class, 503, 544, 566 System.Monitor class, 249 System.Object, 101–103, 154, 243 System.Object types, 550 System.OutOfMemoryException, 103 System.String class, 215, 227, 229, 438 System.Text.Encoding class, 216, 228–230 System.Thread class, 363 ■ INDEX 625 System.Threading namespace, 198 System.Threading.Semaphore class, 402 System.Type namespace, 357 System.Type object, 14 System.TypeInitializationException, 191 System.ValueType, 82 ■ T T identifier, 312, 314 Take extension (LINQ), 562, 565, 573–574 TakeWhile method (LINQ), 562 Task class, 418–420 Task Parallel Library (TPL), 417–418 Parallel class, 420–425 Task class, 418–420 TaskFactory.StartNew() method, 419 TBL (Type Library), 14 template metaprogramming (C++), 501 Template Method pattern, 433 ternary operator, 169, 176 TestForEquality method, 452 text substitution, 238–240 ThenBy extension method (LINQ), 554 this keyword, 49, 51, 74, 85–87, 286 this parameter, 104 Thread class, 363 thread pools, 407–417 asynchronous method calls and, 408–416 entry, using Parallel.Invoke, 425–426 timers and, 416–417 Thread.Abort method, 368–370 Thread.AllocateDataSlot method, 375 Thread.AllocateNamedDataSlot method, 375 Thread.ApartmentState property, 377 Thread.CurrentThread property, 362 Thread.GetHashCode, 363 Thread.Interrupt method, 368, 371 Thread.IsBackground property, 373, 396, 412 Thread.Join method, 363, 368 Thread.ManagedThreadId property, 363 Thread.Priority property, 363 Thread.ResetAbort method, 368, 370 Thread.Resume method, 379 Thread.Sleep method, 368, 371, 379, 383 Thread.Suspend method, 369, 372, 379 ThreadAbortException, 183, 199, 368–371 ThreadFunc method, 362 threads/threading, 361–427 background, 372–373 concurrent programming and, 417–426 creating, 362, 363 events and, 404–405 exceptions, 400 foreground/background threads and, 372– 373 halting, 371–372 locking objects and, 396–402 Monitor class and, 387–396 .NET and, 361–378 passing data to, 363–365 recursion, 400 semaphores and, 402–404 SpinLock class and, 385–387 states of, 366–369, 400 synchronization and, 378–407 terminating/halting threads and, 369–372 unmanaged threads and, 377–378 WaitHandle and, 405–407 waiting for exiting, 372 waking, 371–372 Threading.Interlocked class, 379 ThreadInterruptedException, 368, 371 thread-local storage, 373–377 ThreadPool class, 405, 408 ThreadPool object, 394 ThreadPool.QueueUserWorkItem method, 408 thread-safe collection classes, 426 ThreadStart delegate, 362 ThreadState enumeration, 368 ThreadStaticAttribute attribute, 373 throw statement, 40–41, 182 exception-neutral code and, 194–196 rethrowing exceptions and, 186 throwing exceptions, 182–192 thunks, 279 Timer class, 416 System.Threading namespace, 417 System.WindowsForms namespace, 417 TimerProc method, 417 timers, 416–417 TInput placeholder identifier, 317 TLSClass, 374 TLSFieldClass, 374 ToArray extension method, 575 ToList extension method, 565 ToString method, 102, 463–467 customized, 218 IFormattable class, 218–219, 224–225 IFormatter class, 223 Object class, 225 String.Format method and, 223 TOutput placeholder identifier, 317 TPL. See Task Parallel Library transforms, 497–501 translating exceptions, 187–188 ■ INDEX 626 Troelsen, Andrew, 9 try statement, 183–184 exception-neutral code and, 193 try/catch statement, 20 try/finally statement, 21, 118 TryGetValue method, 259 type casting, 173 type conversion, 30 array covariance, 30–31 boxing conversion, 31 dynamic, 590–592 explicit, 44 generic, 320–321, 347–357 implicit, 44, 63–65 Type Library (TLB), 14 type safety, 309–311 reference types and, 469–473 value types and, 482–484 TypeConverter class, 468 TypeInitializationException, 191, 206 typeof keyword, 14, 358 types, 3, 21–35 anonymous, 88–91 canonical forms and, 429–487 convertibility, 467–469 convertibility and, 247–248 creating own, 43 generic, 34–35 testing, 32–34 See also built-in types ■ U uint type, 21, 24 ulong type, 21, 24 unary operators list, 170 overloading, 169 parameters and, 166 UnaryExpression, 527 unbound delegates, 285–288 unboxing, 94–101 undefined behavior exception, 115 unhandled exceptions, 115, 182, 183 UnhandledExceptionEventArgs, 182 unheld thread mode, 400 unmanaged threads, 377–378 unsafe (unmanaged) code techniques, 26 unspeakable field names, 89 Unstarted state, of threads, 368 upgradeable thread mode, 400 UpgradeToWriterLock method, 399 user-defined value types, 23 ushort type, 21, 24 using keyword, 4, 21, 118–119, 212 deterministic destruction and, 443 disposable objects and, 442 extension methods and, 490 namespaces and, 37 using statement, 21 UTF-16 Unicode character strings, 216 ■ V Validate method, 207 value arguments, 120 value equality, 450, 454 value keyword, 292 value type definitions, 82–88 constructors, 82–84 finalizers, 87 interfaces, 87 this keyword, 85–87 value types, 3, 22–27 canonical forms and, 476–484 checklist for, 429, 486–487 definition, 44 described, 94 Equals override and, 477–481 explicit interface implementation and, 154– 156 interface implementation and, 150, 481 new keyword for, 103 type safety and, 482–484 value equality and, 450 values, terminology and, 26 ValueType class, 481 ValueType.Equals method, 454 var keyword, 28, 89 VarArgs() method, 123 variable capture, 297–300, 533–538 variables, 21–35 default initialization, 27 implicit typing, 526 implicitly typed local, 6, 28–29 reference type, 22–23, 27, 44 type testing, 32–34 variance, 7, 332–334 delegates and, 340–344 rules, 335 vectors, vs. arrays, 249, 251 verbatim strings, 217 Vermeulen, Allan, 366 versioning, 13, 156–157 Virtual Execution Systems (VESs), 2, 9 virtual keyword, 129, 148 ■ INDEX 627 virtual methods, 67–69, 128–132 overriding, 127–131 Visitor pattern, 511–515 Visual Basic, collection types and, 260 Vlissides, John, 137, 433, 511 volatile field modifier, 48 vtables, vs. interface tables, 152 ■ W Wait method, 368, 393 WaitAll method, 406 WaitAny method, 406 WaitHandle class, 402, 405, 407 WaitHandle.WaitAll method, 406 WaitHandle.WaitAny method, 406 WaitHandle.WaitOne method, 404 WaitOne method, 401–406 WaitSleepJoin state, of threads, 368 waking threads, 371 Web Services Description Language (WSDL), 8139 where clause (LINQ), 552–554, 563–564 where keyword, 329 while statement, 20, 39 Win32 functions, 204 Win32 Synchronization objects, 405 write thread mode, 400 write-only properties, 53 ■ X xperf, 422, 423 ■ Y Y fixed-point combinators, 541 ”Yet Another Language Geek” blog, 511 yield blocks, 268–277, 562–563 yield break statement, 270 yield keyword, 262, 268, 317 . 441 Object-Oriented Analysis/Design (OOA/D), 141 object-oriented methodologies, 25 object-oriented programming, 544 objects, 43 copies and, 434–440 C# vs. C++, 27, 430 creating, 103 –113,. class, 101 103 , 154, 243 object initializers, 6 nesting, 92 ■ INDEX 621 syntax, 91–94 uses, 91 object keyword, 101 object references, 44 object type, 22 Object.Equals method, 103 ,. new keyword, 74, 84, 139 class types and, 103 104 member hiding and, 67, 74, 141, 149 method overrides and, 129–131 uses, 103 value types and, 103 new operator, 27, 317 nondeterministic

Ngày đăng: 19/06/2014, 22:20

TỪ KHÓA LIÊN QUAN