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

271 c 4 0 in a nutshell, 4th edition

1,1K 526 0

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.056
Dung lượng 8,08 MB

Nội dung

www.it-ebooks.info www.it-ebooks.info www.it-ebooks.info C# 4.0 IN A NUTSHELL www.it-ebooks.info www.it-ebooks.info C# 4.0 IN A NUTSHELL Fourth Edition Joseph Albahari and Ben Albahari Beijing • Cambridge • Farnham • Kưln • Sebastopol • Taipei • Tokyo www.it-ebooks.info 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 corporate@oreilly.com 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: August 2003: September 2007: January 2010: First Edition Second Edition Third Edition 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 www.it-ebooks.info Table of Contents Preface xiii 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 What’s New in C# 4.0 2 3 C# Language Basics A First C# Program Syntax Type Basics Numeric Types Boolean Type and Operators Strings and Characters Arrays Variables and Parameters Expressions and Operators Statements Namespaces 10 12 21 28 30 32 36 44 48 56 Creating Types in C# 63 Classes Inheritance The object Type 63 76 85 v www.it-ebooks.info Structs Access Modifiers Interfaces Enums Nested Types Generics 89 90 92 97 100 101 Advanced C# 115 Delegates Events Lambda Expressions Anonymous Methods try Statements and Exceptions Enumeration and Iterators Nullable Types Operator Overloading Extension Methods Anonymous Types Dynamic Binding Attributes Unsafe Code and Pointers Preprocessor Directives XML Documentation 115 124 130 134 134 143 148 153 157 160 161 169 170 174 176 Framework Overview 181 The CLR and Core Framework Applied Technologies 183 187 Framework Fundamentals 193 String and Text Handling Dates and Times Dates and Time Zones Formatting and Parsing Standard Format Strings and Parsing Flags Other Conversion Mechanisms Globalization Working with Numbers Enums Tuples The Guid Struct Equality Comparison Order Comparison Utility Classes vi | Table of Contents 193 206 213 219 225 232 235 237 240 244 245 245 255 258 www.it-ebooks.info Collections 263 Enumeration The ICollection and IList Interfaces The Array Class Lists, Queues, Stacks, and Sets Dictionaries Customizable Collections and Proxies Plugging in Equality and Order 263 271 273 282 292 298 304 LINQ Queries 311 Getting Started Fluent Syntax Query Expressions Deferred Execution Subqueries Composition Strategies Projection Strategies Interpreted Queries LINQ to SQL and Entity Framework Building Query Expressions 311 314 320 324 330 333 337 339 346 361 LINQ Operators 367 Overview Filtering Projecting Joining Ordering Grouping Set Operators The Zip Operator Conversion Methods Element Operators Aggregation Methods Quantifiers Generation Methods 369 371 375 387 394 397 400 401 402 404 406 411 412 10 LINQ to XML 413 Architectural Overview X-DOM Overview Instantiating an X-DOM Navigating and Querying Updating an X-DOM Working with Values Documents and Declarations Names and Namespaces 413 414 418 420 425 428 431 434 Table of Contents | vii www.it-ebooks.info Annotations Projecting into an X-DOM 440 441 11 Other XML Technologies 447 XmlReader XmlWriter Patterns for Using XmlReader/XmlWriter XmlDocument XPath XSD and Schema Validation XSLT 448 457 459 463 466 471 474 12 Disposal and Garbage Collection 475 IDisposable, Dispose, and Close Automatic Garbage Collection Finalizers How the Garbage Collector Works Managed Memory Leaks Weak References 475 480 482 487 491 494 13 Diagnostics and Code Contracts 499 Conditional Compilation Debug and Trace Classes Code Contracts Overview Preconditions Postconditions Assertions and Object Invariants Contracts on Interfaces and Abstract Methods Dealing with Contract Failure Selectively Enforcing Contracts Static Contract Checking Debugger Integration Processes and Process Threads StackTrace and StackFrame Windows Event Logs Performance Counters The Stopwatch Class 499 502 506 510 514 517 518 519 521 523 524 525 526 528 530 535 14 Streams and I/O 537 Stream Architecture Using Streams Stream Adapters File and Directory Operations Memory-Mapped Files Compression viii | Table of Contents 537 539 552 559 569 571 www.it-ebooks.info memory barriers and volatility, 825– 830 full memory barriers, 826 shared writable fields, 828 volatile keyword, 828 [NonSerialized] attribute, 630 NotImplementedException, 141 NotSupportedException, 141 null coalescing (??) operator, 152 null keyword, 19 null strings, 196 nullable types, 148–153 alternatives to, 153 boxing and unboxing nullable values, 149 implicit and explicit nullable conversions, 149 operator lifting, 150 operators and, 150–152 bool? with & and |, 151 mixing nullable and non-nullable operators, 151 scenarios, 152 NumberFormatInfo, 222 NumberStyles argument, 227 numeric conversions, 16, 237 numeric type unification, 737 numeric types, 20, 21–28 8- and 16-bit integrals, 25 arithmetic operators, 23 bitwise operators, 25 boolean type, 28–29 double versus decimal types, 27 increment and decrement operators, 24 numeric conversions, 23 numeric literals, 21 numeric suffixes, 22 type inference, 22 real number rounding errors, 27 special float and double values, 26 specialized integral operations, 24 O object initializers, 67, 337 versus optional parameters, 68 object invariant methods (code contracts), 517 1022 | Index object type, 20, 85–88 boxing and unboxing, 86 GetType method and typeof operator, 87 object member listing, 88 static and runtime type checking, 87 ToString method, 88 Object.Equals method, 247 ObjectContext, 350–354 disposing, 352 object tracking, 352 ObjectDisposedException, 141 OfType query operator, 402 opcodes Add (add), 709 Br, Brtrue, and Blt (branch), 711 Call (call a method), 708 Callvirt (virtual call), 712 Div(divide), 709 EmitWriteLine, 707 Ldarg_0 (push arg onto stack) , 709 Ldc_i4 (push 4-byte integer), 709 ldfld (load a field), 720 Ldind (load indirectly), 719 Ldloc (load a local variable), 710 Ldstr (load a string), 708 Mul (multiply), 711 Newobj (new object), 712 Pop (remove from stack), 710 Ret (return), 707 stfld (store to a field), 721 Stind (store indirectly), 719 Stloc (store a local variable), 710 Throw (throw exception), 713 open generic types, 102 operator functions, 154 operator lifting, 150 operator overloading, 153–156 equality and comparison operators, 155 implicit and explicit conversions, 155 operator functions, 154 true and false operators, 156 operators, 12, 44–48 arithmetic operators, 23 bitwise operators, 25 conditional operators, 29 equality and comparison operators, 28 www.it-ebooks.info increment and decrement operators, 24 precedence and associativity, 46 table of operators, 46 optional parameters, 5, 42 or (||) operator, 29 order comparison, 199, 255–257 < and > operators, 257 IComparable interfaces, 256 implementation, 257 OrderBy operator, 314 OrderedDictionary class, 292, 295 ordinal comparisons, 199 out modifier, 40, 111 outer variables, 132 overflow checking, 25 overloading inheritance, impact on method overloading, 84 operator overloading, 153 override keyword, 80 P P/Invoke (Platform Invocation Services), 957 PadRight and PadLeft, 197 documentation tag, 178 Parallel class, 892–898 Parallel.For and Parallel.ForEach, 893 breaking out of loops, 895 indexed Parallel.ForEach, 894 optimization with local values, 896 outer versus inner loops, 894 Parallel.Invoke, 892 Parallel Framework (see PFX) Parallel LINQ (see PLINQ) parallel programming, 874, 876 PFX (see PFX) parallel queries, 879 documentation tag, 177 parameterless constructors, 66 parameters, 8, 38–44 named arguments, 43 object initializers versus optional parameters, 68 optional parameters, 42 out modifier, 40 params modifier, 41 passing arguments by value, 39 passing by reference, implications, 41 ref parameter modifier, 39 documentation tag, 178 parentheses ( ), 12 regex alternator, 978 regex lookahead and lookbehind, 983 regex named groups, 987 Parse method, 210 ParseExact method, 210 parsing, 219 DateTime and DateTimeOffset, 212, 230 DateTimeStyles and, 231 enum format strings, 231 with format providers, 223 Parse method, 220 parsing and misparsing of DateTimes, 230 TryParse method, 220 type converters, 234 partial classes, 75 partial methods, 76 partially trusted callers, 758 passing by reference ref modifier, 39 password hashing, 778 Path class, 559, 564 PE (Portable Executable) file, 647 Peek method, 288 performance counters, 530–535 creating counters, 533 enumeration of available counters, 531 reading counter data, 532 writing performance data, 533 period (.), 12 regex character matching, 981 documentation tag, 177 permissions, 751–755 CodeAccessPermission and PrincipalPermission, 752 IPermission interface, 753 declarative versus imperative security, 755 PermissionSet, 754 PFX (Parallel Framework), 874–877 PIA (Primary Interop Assembly), 975 Index | 1023 www.it-ebooks.info PipeStream class, 547 anonymous pipes, 550 named pipes, 548 PLINQ (Parallel LINQ), 877–891 calls to blocking or I/O-intensive functions, 884 cancellation of queries, 886 functional purity, 883 limitations, 880 occasions for use, 883 optimization, 886–891 custom aggregations, 889 input-side, 887 ordering and, 880 parallel execution ballistics, 879 parallel spellchecker example, 881 partitioning strategies, 887 plug-ins, sandboxing, 769 plus (+) operator, 31, 117 pointer-to-member (->) operator, 171, 172 pointers, 3, 171 arrays and, 172 fixed-size buffers, 173 pointer operators, 171 to unmanaged code, 174 unsafe code and, 170–174 void pointers, 173 polymorphism, 77 Pop method, 288 POP3, 606 positional attribute parameters, 169 positive lookahead, 983 positive lookbehind, 984 pragma warning, 175 precedence of operators, 46 predefined types, 13 predefined type taxonomy, 20 predicates in LINQ, 279, 316 prefixes (XML), 435, 439 preprocessor directives, 174–176, 499 pragma warning, 175 Primary Interop Assembly (PIA), 975 primitive types, 20 PrincipalPermission, 752 PrincipalPermission class, 775 private access modifier, 90 private working set, 481 1024 | Index PrivateBinPath property, 946 Process class, 260, 525 processes, 525 running processes, examining, 526 threads in, examining, 526 projection (LINQ), 315 properties, 69, 70 protected access modifier, 90 protected internal access modifier, 90 ProtectedData class, 777 proxy servers, 587 public access modifier, 90 Public Key Encryption, 776 public key encryption digital signing, 787 RSA class, 786 public keyword, 16 Push method, 288 Q quantifiers (LINQ), 319 quantifiers (regex), 977 queries, 312 query expression syntax, 313 query expressions, 320 building, 361–366 AsQueryable operator, 362 delegates versus expression trees, 361 expression trees, 363–366 expression trees, compiling, 362 query strings (HTTP), 593 query syntax, 320 versus SQL syntax, 322 question mark (?) conditional operator, 29 in nullable types, 149 regex quantifier, 977 Queue class, 287 Queue, 287 QueueUserWork Item method, 802 R Random class, 239 RandomNumberGenerator (cryptographically strong), 781 range partitioning, 888 www.it-ebooks.info Range query operator, 412 range variables (LINQ), 320, 322 RCWs (Runtime-Callable Wrappers), 971 read-only properties, 70 Reader/Writer locks, 865–869 readonly modifier, 64 ReadOnlyCollection, 303 real number rounding, 27 real number types, 21 rectangular arrays, 33 recursion, 36 ref modifier, 39 ref parameter modifier, 39 reference conversions, 16, 78 reference types, 17, 18 in arrays, 33 classes (see classes) nulls, 19 predefined, 20 ReferenceEquals method, 249 references, 39 weak references, 494–498 caching and, 495 events and, 496 referential equality, 246 reflection, 681 assemblies, reflecting, 700 assembly loading, reflection-only context, 700 modules, 701 circular dependencies, 726 dynamic code generation (see dynamic code generation) emitting assemblies and types, 714– 717 Reflection.Emit object model, 716 saving emitted assemblies, 715 emitting generic methods and types, 723–724 emitting type members, 717–722 attaching attributes, 722 constructors, 721 emitting methods, 718 fields and properties, 719 methods, 718 IL, parsing, 728–733 members, reflecting and invoking, 688–699 C# members versus CLR members, 691 delegates, 695 dynamic invocation, 693 generic methods, 697 generic type members, 692 member types, 690 members of generic interfaces, 697– 699 method parameters, 693–695 nonpublic members, accessing, 696 Reflection.Emit object model, 716 types, reflecting and activating, 682– 688 base types and interfaces, 685 generic types, 687 instantiating types, 685 obtaining types, 682 type names, 683 uncreated closed generics, 725 RegEx method, 978 Regex.Match, 978 regular expressions, 977 character categories, 993 character escapes, 980 character sets, 981, 992 compiled regular expressions, 978 cookbook recipes, 988–991 groups, 985 named groups, 986 language reference, 992–995 options, 979 quantifiers, 982, 993 greedy versus lazy quantifiers, 982 RegexOptions flags enum, 979 replacing and splitting text, 987 MatchEvaluator delegate, 988 Regex.Split method, 988 zero-width assertions, 983 anchors, 984 lookahead and lookbehind, 983 word boundary assertions, 985 reimplementing an interface, 94 relational operators, 151 documentation tag, 177 Index | 1025 www.it-ebooks.info Remoting, 952 remove keyword, 124 Remove method (string), 197 Repeat query operator, 412 Resize method (arrays), 282 ResourceManager class, 667 resources, 663–669 direct embedding of, 664 pack URI resources, creating in Visual Studio, 668 resource files, 666 reading, 667 resource localization, 669 resx files, 666 creating via command line, 667 resueection GC.ReRegisterForFinalize, 486 rethrowing an exception, 139 documentation tag, 177 return statement, 56 Reverse query operator, 319 ReverseEcho class, 934 right-associative operators, 46 Rijndael class, 780 role-based security, 775 roots for garbage collection, 482 rounding errors, real numbers, 27 rounding numeric conversions, 232 RSA class, 786 RSACryptoServiceProvider class, 788 Runtime-Callable Wrappers (RCWs), 971 RuntimeBinderException, 164 S safe cancellation (threads), 857–860 sandboxing, 751, 758 sandboxing another assembly, 769 satellite assemblies, 669–670 sbyte integral type, 25 sealing functions and classes, 82 security, 751 CAS, 755–758 cryptography (see cryptography) declarative versus imperative security, 755 identity and role security, 775–776 isolated storage (see isolated storage) 1026 | Index operating system security, 772–775 partially trusted callers, 758 APTCA and [SecurityTransparent], 759 elevation of privilege attack, 759 permissions (see permissions) sandboxing plug-ins, 769 security transparency model, CLR 4.0, 761–772 standard user account restrictions, 773 Windows Data Protection, 777 [SecurityTransparent], 759 documentation tag, 178 documentation tag, 178 Select query operator, 314, 376 selection statements, 50–53 SelectMany query operator, 380–387 Semaphore class, 816 semicolon (;), 7, 12 SequenceEqual query operator, 411 sequences (LINQ), 311 [Serializable] attribute, 629 serialization, 609–613 (see also data contract serializers) serialization engines, 610–612 binary serializers (see binary serializers) IXmlSerializable interface (see IXmlSerializable interface) XmlSerializer (see XmlSerializer engine) SetCustomAttribute method, 722 SetData and GetData, 864 SHA256, 779 shared memory, 569, 963 shift left () operator, 25 short integral type, 25 side-by-side execution, 663 SignalAndWait, WaitAny, and WaitAll, 839 signaling, 832 with event wait handles (see event wait handles) with Wait and Pulse (see Wait and Pulse1) www.it-ebooks.info Silverlight, 188 Single query operator, 405 single quotes ('), 30 single-line comments, 12 single-threaded timers, 871 sizeof operator, 47, 173 Skip query operator, 319, 374 SkipWhile query operator, 375 SmtpClient class, 603 sn (strong-name) utility, 653 SortedDictionary, 296 SortedList class, 292 SortedList class, 292 SortedSet, 289 SpecialFolder enum, 566 SpinLock struct, 920 spinning, 808 SpinWait struct, 922–925 Split method, 197 square brackets ([ ]) arrays, 9, 32 attributes, 172 in regular expressions, 978, 981 indexers, 71 SSL, 596 stack, 36, 85 Stack class, 288 Stack, 288 stackalloc keyword, 172 StackTrace and StackFrame classes, 526– 528 standard numeric format strings, 225 standard query operators, 311, 369 StartsWith method, 196 statement blocks, statements, 7, 48–56 break statement, 55 continue statement, 55 declaration statements, 48 expression statements, 49 fixed statement, 171 for loops, 53 foreach loops, 54 foreach statement, 143 goto statement, 55 if statement, 50 iteration statements, 53–54 jump statements, 54–56 lock statement, 56 return statement, 56 selection statements, 50–53 switch statement, 52 throw statement, 56 try statement, 134–143 using statement, 56 while and do-while loops, 53 yield break statement, 146 yield return statement, 147 static binding, 161, 693 static classes, 74, 559 static constructors, 73 static contract checking, 523–524 baselines, 524 ContractVerification attribute, 524 SuppressMessage attribute, 524 static members, 15 thread safety, 820 Stopwatch class, 535 stream adapters, 552–559 binary adapters, 557 closing and disposing, 558 text adapters, 553–557 Stream class, 537 StreamReader, 554 streams, 537 adapters, 538 backing store streams, 538, 543 BufferedStream class, 551 closing and flushing, 542 compression, 571 decorator streams, 538 FileStream class, 543 isolated storage (see isolated storage) MemoryStream class, 546 PipeStream class, 547 reading and writing, 540 seeking, 542 stream adapters (see stream adapters) stream architecture, 537 thread safety, 543 timeouts, 542 StreamWriter, 554 string.IsNullOrEmpty method, 196 StringComparer class, 308 StringComparison enum, 200 StringInfo class Index | 1027 www.it-ebooks.info two-word characters and, 206 StringReader, 557 strings, 30–31, 195–203 characters, accessing within strings, 196 comparing strings, 199–202 equality comparisons, 200 ordinal versus culture comparisons, 199 constructing, 195 escape sequences, 31 Format method, 198 formatting (see formatting) indexers, 196 manipulating, 197 null and empty strings, 195 searching within, 196 splitting and joining, 197 string comparisons string order comparisons, 201 StringBuilder class, 202 releasing memory, 203 text encodings and unicode, 203–206 StringWriter, 557 strong-name-signing, 652 StrongName object, 771 struct generic constraint, 107 StructLayout attribute, 960 structs, 89, 310 construction semantics, 89 Equals method, 251 mapping to unmanaged memory, 965 fixed and fixed {…}, 968 parameterless constructors and, 66 simulating a C union, 962 speeding up equality comparisons, 251 structural equality, 246 subqueries deferred execution and, 332 subqueries (LINQ), 330–333 Substring method, 197 subtract from self (-=) operator, 117 suffixes for numeric literals, 22 Sum query operator, 408 documentation tag, 177 SurnameComparer example, 308 surrogate character pairs, 206 1028 | Index switch statement, 52 symmetric encryption, 776, 780 synchronization context scheduler, 909 synchronization of threads, 805 syntax, 10–12 comments, 12 identifiers and keywords, 10 literals, punctuators and operators, 12 System.Attribute class, 169 System.Collections namespaces, 263 System.Numerics.dll, 239 System.Reflection.Emit namespace, 716 System.Security.Cryptography namespaces, 777 System.Threading.Timer, 870 T Take query operator, 319, 374 TakeWhile query operator, 375 Target property (System.Delegate class), 118 Task class, 904 Task Parallel Library (TPL), 800 task parallelism, 874, 898–912 task schedulers and UIs, 909 TaskCompletionSource class, 911 TaskFactory, 910 tasks (see tasks) tasks, 898 canceling, 903 coninuations conditional continuations, 907 continuations, 904–909 child tasks and, 906 exceptions and, 905 with multiple antecedents, 908 multiple continuations on one antecedent, 909 Task, 905 creating and starting, 899 child tasks, 901 specifying state objects, 900 TaskCreationOptions, 900 exception-handling tasks, 902 waiting on tasks, 901 TCP, 582, 604 TcpClient and TcpListener classes, 604 text encoding www.it-ebooks.info byte arrays, encoding to, 205 UTF-16 and surrogate pairs, 205 text encodings, 203–206 Encoding class, 204 file and stream I/O, encoding for, 204 text encodings and text encoders, 203 TextReader and TextWriter classes, 553 this keyword (overloading constructors), 66 this reference, 68 thread safety, 817–825 NET Framework types and read-only thread safety, 820 static methods, 820 thread-safe objects, locking around, 819 application servers, 821 immutable objects, 823 NET Framework types and, 818 rich clients and thread affinity, 822 worker threads versus UI threads, 823 threading, 789–793 BackgroundWorker class, 852 Barrier class, 849 blocking, 792 EAP, 851 event wait handles (see event wait handlies) exception handling, 798–800, 799 foreground and background threads, 796 lazy initialization, 860–862 Lazy class, 861 LazyInitializer class, 861 locking, 808–817 deadlocks, 813–815 Monitor.Enter and Monitor.Exit (see Monitor.Enter and Monitor.Exit) Mutex class, 815 nested locking, 813 performance, 815 Semaphore class, 816 synchronization objects, choosing, 811 when to lock, 811 nonblocking synchronization (see nonblocking synchronization) passing data to threads, 793–795 Lambda expressions and captured variables, 794 preemption, 792 priority, 797 Reader/Writer locks, 865–869 reader/writer locks, 867 recursion, 868 safe cancellation cancellation tokens, 859 sharing data between threads, 795 signaling, 832 Wait and Pulse (see Wait and Pulse) synchronization, 805–808 blocking, 807 blocking versus spinning, 808 thread execution barriers, 849 thread pooling, 800–807 thread pools asynchronous delegates, 803 entry with TPL, 801 entry without TPL, 802–805 optimization, 805 QueueUserWorkItem method, 802 thread safety (see thread safety) thread-agnostic classes, 816 thread-local storage, 862–865 GetData and SetData, 864 ThreadLocal class, 863 [ThreadStatic] attribute, 863 Thread.Sleep method, 792 timers, 869–872 multithreaded timers, 870 single-threaded timers, 871 uses, 789 ThreadLocal, 882 ThreadPool.RegisterWaitForSingleObject , 941 threads, 789 throw statement, 56 throwing exceptions, 139 tilde (~) finalizers, 74 tilde (~),complement operator, 25 time zones Index | 1029 www.it-ebooks.info DateTime and, 213 DateTimeOffset and, 214 TimeZone, 214 TimeZone.CurrentTimeZone method, 214 TimeZoneInfo, 215–218 timers, 869–872 multithreaded timers, 870 single-threaded timers, 871 timers and memory leaks, 493 TimeSpan, 206 TimeZone, 214 TimeZoneInfo, 214 ToArray query operator, 404 ToCharArray method, 195 ToDictionary query operator, 404 ToList query operator, 404 ToLookup query opperator, 404 ToLower method, 193, 197 ToShortDateString and ToLongDateString methods, 212 ToString method, 88 ToUpper and ToLower methods, 193 ToUpper method, 193, 197 TPL (Task Parallel Library), 800 Trace class, 502–506 Fail and Assert methods, 503 Listeners property, 504 flushing and closing Listeners, 505 TraceListener, 504 TrimStart and TrimEnd, 197 true operator, overloading, 156 try statement, 134–143 catch clause, 136 finally block, 137 throwing exceptions, 139 TryEnter method, 810 TryGetValue method, 293 TryParse method, 220 tuples, 244 comparing, 244 type conversions Convert class (see Convert class) dynamic type conversion, 165 XmlConvert class (see XmlConvert class) type converters, 234 1030 | Index type discovery, 955 type marshaling, 958–961 type parameters and type arguments, 102 TypeConverter class, 234 typeof operator, 87, 105, 682 types, 12–20 anonymous types, 160 classes (see classes) constructors and instantiation, 14 custom types, 14 data members and function members, 14 delegates, 115–123 enums, 97–100 generic types, 102 instance versus static members, 15 interfaces, 92–97 nested types, 100 object type, 85–88 predefined types, 13, 20 structs, 89 type conversions, 16 type names, 683 value types versus reference types, 16– 20, 19 U UAC (User Access Control), 773 UDP, 582, 604 UI threads, 823 uint or ulong types suffixes, 22 unary operators overloading of, 153 unbound generic types, 105 unboxing, 85 nullable values, boxing and unboxing, 149 uncallable functions, 168 unchecked operator, 25 Unicode, 203 Union query operator, 400 UnionWith method, 291 unsafe keyword, 171 (see also native interoperability) upcasting, 78 URIs, 582–584 Uri class, 582 www.it-ebooks.info ushort integral type, 25 using directive, 57 contrasted with using statement, 56 nested using directives, 59 using statement, 56, 138 UTC, 208 UTF-8, UTF-16, and UTF-32, 203 utility classes, 258–261 Console class, 258 Environment class, 260 Process class, 260 V value equality, 246 value types, 17 in arrays, 33 nullable types and, 149 predefined, 20 var keyword, 44, 160 variables, 12, 36–44 captured variables, 132 default values, 38 definite assignment, 37 heap, 36 implicitly typed local variables, 44 stack, 36 verbatim string literals, 31 versioning (assemblies), 655, 656 versioning (assembly informational), 657 Versioning (with GAC), 663 vertical bar (|) regex alternator, 978 with enums, 98 with nullable types, 151 virtual function members, 79 virtual keyword, 79 virtualization, 775 Visitor pattern, 738–741 void keyword, volatile keyword, 828 W Wait and Pulse, 840–849 producer/consumer queue, 844–847 simulating Wait handles, 848 Wait timeout, 847 WaitAny, WaitAll, and SignalAndWait, 839 Warnings, compiler pragma warning, 175 weak references, 494 WeakReference class, 494–498 WebClient, 584 WebExceptionStatus enum, 591 WebProxy, 587 WebRequest and WebResponse classes, 585–587 WebRequestMethods.FTP, 600 Where query operator, 314, 372 while loops, 53 Windows authentication (networking), 587 Windows Data Protection, 776, 777 Windows event logs, 528–530 monitoring, 530 reading, 529 writing to, 528 Windows Forms, 187, 189 Windows Forms libraries thread affinity, 822 Windows Presentation Foundation, 187 Windows Workflow, 190 WithDegreeOfParallelism method, 884 WMI, 561 word boundary assertions (regex), 984 worker threads, 823 working set, 481 WPF (Windows Presentation Foundation), 188 thread affinity, 822 Write and WriteLine methods, 259 WriteAllText method, 204 X X-DOM, 414–417, 414 (see also LINQ to XML) annotations, 440 documents and declarations, 431–434 XDocument, 431 XML declarations, 433 instantiating, 418–420 automatic deep cloning, 420 content, specifying, 419 functional construction, 418 Index | 1031 www.it-ebooks.info loading and parsing, 416 names and namespaces, 434–440 default namespaces, 438 prefixes, 439 specifying namespaces, 437 XML namespaces, 435 navigating and querying, 420–425 attribute navigation, 425 child node navigation, 420–423 parent navigation, 424 peer node navigation, 425 projecting into, 441–446 empty elements, eliminating, 443 streaming projections, 443 transforming X-DOMs with reprojection, 444 saving and serializing, 417 updating, 425–428 child nodes and attributes, 426 simple value updates, 426 through the parent, 427 values, working with, 428–431 automatic XText concatenation, 430 getting values, 429 mixed content nodes and, 430 setting, 429 XmlReader and XmlWriter, mixing with, 461 XAML (Extensible Application Markup Language), 234 XDocument, 414 XElement type, 414 XML documentation, 176 standard documentation tags, 177 type prefixes, 179 user-defined tags, 178 XML namespaces, 435 attributes, 436 prefixes, 435 specifying in X-DOM, 437 XML nodes, 449 reading, 449 XML Schema Definition (see XSD) XML serailization (see XmlSerializer engine; IXmlSerializable interface) XmlConvert class, 234 1032 | Index XmlDocument, 463–466 InnerText and InnerXml, 464 loading and saving, 463 namespaces, 466 nodes, creating and manipulating, 465 traversing, 464 XmlElementAttribute constructor, 722 XmlNodeType, 449 XmlReader class, 448–456 attributes, reading, 454 attribute nodes, 455 start element positioning, 455 elements reading validation failure, 451 elements, reading, 451–454 empty elements, 452 optional elements, 452 random element order, 452 Read methods, 453 namespaces, 456 nodes, reading, 449–451 patterns for use, 459–463 X-DOM, mixing with, 461 XElement, usage with, 461 XmlSerializer engine, 611, 637–644 attribute-based serialization, 637 attributes, names, and namespaces, 639 XML element order, 639 collections, serializing, 642 subclassed collection elements, 644 subclasses and child object, 639 serializing child objects, 640 subclassing child objects, 641 XmlWriter class, 457–458 attributes, writing, 458 namespaces and prefixes, 458 patterns for use, 459–463 X-DOM, mixing with, 461 XElement, using with, 462 XNode class, 415 XObject class, 415 XPath, 466–470 common operators, 468 namespaces, querying with, 470 writing queries within code, 467 XPathDocument, 470 www.it-ebooks.info XPathNavigator, 469 XSD (XML Schema Definition), 471–474 schema validation, 472 on X-DOMs and XmlDocuments, 473 XmlReader, using, 472 XSLT (Extensible Stylesheet Language Transformations), 474 XStreamingElement, 443 Y yield break statement, 146 yield return statement, 147 Z zero-width assertions, 983 Zip query operator, 401 Index | 1033 www.it-ebooks.info www.it-ebooks.info About the Authors Joe Albahari is the author of LINQPad and other C# tools, and he writes about C# at http://www.albahari.com/nutshell/ He is a C# MVP and has been developing large-scale applications on NET and other platforms for more than 15 years Joe is currently a freelance consultant Ben Albahari is a former program manager at Microsoft and has been a coauthor of C# in a Nutshell since the first edition He is the founder of TakeOnIt, a website for comparing opinions of experts, leaders, and organizations on important topics Colophon The animal on the cover of C# 4.0 in a Nutshell is a numidian crane The Numidian crane (Antropoides virgo) is also called the demoiselle crane because of its grace and symmetry This species of crane is native to Europe and Asia and migrates to India, Pakistan, and northeast Africa in the winter Though numidian cranes are the smallest cranes, they defend their territories as aggressively as other crane species, using their loud voices to warn others of trespassing If necessary, they will fight Numidian cranes nest in uplands rather than wetlands and will even live in the desert if there is water within 200 to 500 meters They sometimes make nests out of pebbles in which to lay their eggs, though more often they will lay eggs directly on the ground, protected only by spotty vegetation Numidian cranes are considered a symbol of good luck in some countries and are sometimes even protected by law The cover image is an original engraving from the 19th century The cover font is Adobe ITC Garamond The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont’s TheSansMonoCondensed www.it-ebooks.info Download at WoweBook.com ... Introducing C# and NET What’s New in C# 4.0 The new features in C# 4.0 are: • Dynamic binding • Type variance with generic interfaces and delegates • Optional parameters • Named arguments • COM interoperability... method can also optionally accept an array of strings as a parameter (that will be populated with any arguments passed to the executable) For example: static int Main (string[] args) { } | Chapter... means an interface A line with a hollow triangle denotes inheritance, with the triangle pointing to the base type A line with an arrow denotes a one-way association; a line without an arrow denotes

Ngày đăng: 06/03/2019, 16:36