Tài liệu học c mới nhất. ToObject is overloaded to accept all integral types as well as object. (Thelatter works with any boxed integral type.)String conversionsTo convert an enum to a string, you can either call the static Enum.Formatmethod or call ToString on the instance. Each method accepts a formatstring, which can be G for default formatting behavior, D to emit theunderlying integral value as a string, X for the same in hexadecimal, orF to format combined members of an enum without the Flags attribute.We listed examples of these in “Standard Format Strings and ParsingFlags”. Enum.Parse converts a string to an enum. It accepts the enum type and astring that can include multiple members:BorderSides leftRight = (BorderSides) Enum.Parse (typeof (BorderSides), Left, Right);An optional third argument lets you perform caseinsensitive parsing. AnArgumentException is thrown if the member is not found.Enumerating Enum ValuesEnum.GetValues returns an array comprising all members of a particularenum type:foreach (Enum value in Enum.GetValues (typeof (BorderSides))) Console.WriteLine (value);Composite members such as LeftRight = Left | Right are included
C# 9.0 in a Nutshell The Definitive Reference Joseph Albahari C# 9.0 in a Nutshell by Joseph Albahari Copyright © 2021 Joseph 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://oreilly.com) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com Acquisitions Editor: Amanda Quinn Development Editor: Corbin Collins Production Editor: Kristen Brown Copyeditor: Charles Roumeliotis Proofreader: Piper Editorial Consulting, LLC Indexer: WordCo Indexing Services, Inc Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea March 2021: First Edition Revision History for the First Edition 2021-02-26: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098100964 for release details The O’Reilly logo is a registered trademark of O’Reilly Media, Inc C# 9.0 in a Nutshell, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc The views expressed in this work are those of the author, and not represent the publisher’s views While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim 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 technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights 978-1-098-10096-4 [LSI] Preface C# 9.0 represents the eighth major update to Microsoft’s flagship programming language, positioning C# as a language with unusual flexibility and breadth At one end, it offers high-level abstractions such as query expressions and asynchronous continuations, whereas at the other end, it allows low-level efficiency through constructs such as custom value types and optional pointers The price of this growth is that there’s more than ever to learn Although tools such as Microsoft’s IntelliSense—and online references—are excellent in helping you on the job, they presume an existing map of conceptual knowledge This book provides exactly that map of knowledge in a concise and unified style—free of clutter and long introductions Like the past six editions, C# 9.0 in a Nutshell is organized around concepts and use cases, making it friendly both to sequential reading and to random browsing It also plumbs significant depths while assuming only basic background knowledge, making it accessible to intermediate as well as advanced readers This book covers C#, the Common Language Runtime (CLR), and the NET Base Class Library (BCL) We’ve chosen this focus to allow space for difficult and advanced topics without compromising depth or readability Features recently added to C# are flagged so that you can also use this book as a reference for C# and C# Intended Audience This book targets intermediate to advanced audiences No prior knowledge of C# is required, but some general programming experience is necessary For the beginner, this book complements, rather than replaces, a tutorialstyle introduction to programming This book is an ideal companion to any of the vast array of books that focus on an applied technology such as ASP.NET Core or Windows Presentation Foundation (WPF) C# 9.0 in a Nutshell covers the areas of the language and NET that such books omit, and vice versa If you’re looking for a book that skims every NET technology, this is not for you This book is also unsuitable if you want to learn about APIs specific to mobile device development How This Book Is Organized Chapters through concentrate purely on C#, starting with the basics of syntax, types, and variables, and finishing with advanced topics such as unsafe code and preprocessor directives If you’re new to the language, you should read these chapters sequentially The remaining chapters focus on NET 5’s Base Class Libraries, covering such topics as Language-Integrated Query (LINQ), XML, collections, concurrency, I/O and networking, memory management, reflection, dynamic programming, attributes, cryptography, and native interoperability You can read most of these chapters randomly, except for Chapters and 6, which lay a foundation for subsequent topics You’re also best off reading the three chapters on LINQ in sequence, and some chapters assume some knowledge of concurrency, which we cover in Chapter 14 What You Need to Use This Book The examples in this book require NET You will also find Microsoft’s NET documentation useful to look up individual types and members (which is available online) Although it’s possible to write source code in Notepad and build your program from the command line, you’ll be much more productive with a code scratchpad for instantly testing code snippets, plus an integrated development environment (IDE) for producing executables and libraries For a Windows code scratchpad, download LINQPad from www.linqpad.net (free) LINQPad fully supports C# 9.0 and is maintained by one of the authors For a Windows IDE, download Visual Studio 2019: any edition is suitable for what’s taught in this book For a cross-platform IDE, download Visual Studio Code NOTE All code listings for all chapters are available as interactive (editable) LINQPad samples You can download the entire lot in a single click: at the bottom left, click the LINQPad’s Samples tab, click “Download more samples,” and then choose “C# 9.0 in a Nutshell.” Conventions Used in This Book The book uses basic UML notation to illustrate relationships between types, as shown in Figure P-1 A slanted rectangle means an abstract class; a circle 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 oneway association; a line without an arrow denotes a two-way association Figure P-1 Sample diagram The following typographical conventions are used in this book: Italic Indicates new terms, URIs, filenames, and directories Constant width Indicates C# code, keywords and identifiers, and program output Constant width bold Shows a highlighted section of code Constant width italic Shows text that should be replaced with user-supplied values NOTE This element signifies a general note WARNING This element indicates a warning or caution Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at http://www.albahari.com/nutshell If you have a technical question or a problem using the code examples, please send email to bookquestions@oreilly.com vi Asynchrony and Synchronization Contexts vii Optimizations f Asynchronous Patterns i Cancellation ii Progress Reporting iii The Task-Based Asynchronous Pattern iv Task Combinators v Asynchronous Locking g Obsolete Patterns i Asynchronous Programming Model ii Event-Based Asynchronous Pattern iii BackgroundWorker 16 15 Streams and I/O a Stream Architecture b Using Streams i Reading and Writing ii Seeking iii Closing and Flushing iv Timeouts v Thread Safety vi Backing Store Streams vii FileStream viii MemoryStream ix PipeStream x BufferedStream c Stream Adapters i Text Adapters ii Binary Adapters iii Closing and Disposing Stream Adapters d Compression Streams i Compressing in Memory ii Unix gzip File Compression e Working with ZIP Files f File and Directory Operations i The File Class ii The Directory Class iii FileInfo and DirectoryInfo iv Path v Special Folders vi Querying Volume Information vii Catching Filesystem Events g File I/O in UWP i Working with Directories ii Working with Files iii Obtaining Directories and Files h OS Security i Running in a Standard User Account ii Administrative Elevation and Virtualization i Memory-Mapped Files i Memory-Mapped Files and Random File I/O ii Memory-Mapped Files and Shared Memory (Windows) iii Cross-Platform Interprocess Shared Memory iv Working with View Accessors 17 16 Networking a Network Architecture b Addresses and Ports c URIs d Client-Side Classes i WebClient ii WebRequest and WebResponse iii HttpClient iv Proxies v Authentication vi Exception Handling e Working with HTTP i Headers ii Query Strings iii Uploading Form Data iv Cookies f Writing an HTTP Server g Using FTP h Using DNS i Sending Mail with SmtpClient j Using TCP i Concurrency with TCP k Receiving POP3 Mail with TCP l TCP in UWP 18 17 Assemblies a What’s in an Assembly i The Assembly Manifest ii The Application Manifest (Windows) iii Modules iv The Assembly Class b Strong Names and Assembly Signing i How to Strongly Name an Assembly c Assembly Names i Fully Qualified Names ii The AssemblyName Class iii Assembly Informational and File Versions d Authenticode Signing i How to Sign with Authenticode e Resources and Satellite Assemblies i Directly Embedding Resources ii .resources Files iii .resx Files iv Satellite Assemblies v Cultures and Subcultures f Loading, Resolving, and Isolating Assemblies i Assembly Load Contexts ii The Default ALC iii The “Current” ALC iv Assembly.Load and Contextual ALCs v Loading and Resolving Unmanaged Libraries vi AssemblyDependencyResolver vii Unloading ALCs viii The Legacy Loading Methods ix Writing a Plug-In System 19 18 Reflection and Metadata a Reflecting and Activating Types i Obtaining a Type ii Type Names iii Base Types and Interfaces iv Instantiating Types v Generic Types b Reflecting and Invoking Members i Member Types ii C# Members Versus CLR Members iii Generic Type Members iv Dynamically Invoking a Member v Method Parameters vi Using Delegates for Performance vii Accessing Nonpublic Members viii Generic Methods ix Anonymously Calling Members of a Generic Interface c Reflecting Assemblies i Modules d Working with Attributes i Attribute Basics ii The AttributeUsage Attribute iii Defining Your Own Attribute iv Retrieving Attributes at Runtime e Dynamic Code Generation i Generating IL with DynamicMethod ii The Evaluation Stack iii Passing Arguments to a Dynamic Method iv Generating Local Variables v Branching vi Instantiating Objects and Calling Instance Methods vii Exception Handling f Emitting Assemblies and Types i The Reflection.Emit Object Model g Emitting Type Members i Emitting Methods ii Emitting Fields and Properties iii Emitting Constructors iv Attaching Attributes h Emitting Generic Methods and Types i Defining Generic Methods ii Defining Generic Types i Awkward Emission Targets i Uncreated Closed Generics ii Circular Dependencies j Parsing IL i Writing a Disassembler 20 19 Dynamic Programming a The Dynamic Language Runtime b Numeric Type Unification c Dynamic Member Overload Resolution i Simplifying the Visitor Pattern ii Anonymously Calling Members of a Generic Type d Implementing Dynamic Objects i DynamicObject ii ExpandoObject e Interoperating with Dynamic Languages i Passing State Between C# and a Script 21 20 Cryptography a Overview b Windows Data Protection c Hashing i Hash Algorithms in NET ii Hashing Passwords d Symmetric Encryption i Encrypting in Memory ii Chaining Encryption Streams iii Disposing Encryption Objects iv Key Management e Public-Key Encryption and Signing i The RSA Class ii Digital Signing 22 21 Advanced Threading a Synchronization Overview b Exclusive Locking i The lock Statement ii Monitor.Enter and Monitor.Exit iii Choosing the Synchronization Object iv When to Lock v Locking and Atomicity vi Nested Locking vii Deadlocks viii Performance ix Mutex c Locking and Thread Safety i Thread Safety and NET Types ii Thread Safety in Application Servers iii Immutable Objects d Nonexclusive Locking i Semaphore ii Reader/Writer Locks e Signaling with Event Wait Handles i AutoResetEvent ii ManualResetEvent iii CountdownEvent iv Creating a Cross-Process EventWaitHandle v Wait Handles and Continuations vi WaitAny, WaitAll, and SignalAndWait f The Barrier Class g Lazy Initialization i Lazy ii LazyInitializer h Thread-Local Storage i [ThreadStatic] ii ThreadLocal iii GetData and SetData iv AsyncLocal i Timers i Multithreaded Timers ii Single-Threaded Timers 23 22 Parallel Programming a Why PFX? i PFX Concepts ii PFX Components iii When to Use PFX b PLINQ i Parallel Execution Ballistics ii PLINQ and Ordering iii PLINQ Limitations iv Example: Parallel Spellchecker v Functional Purity vi Setting the Degree of Parallelism vii Cancellation viii Optimizing PLINQ c The Parallel Class i Parallel.Invoke ii Parallel.For and Parallel.ForEach d Task Parallelism i Creating and Starting Tasks ii Waiting on Multiple Tasks iii Canceling Tasks iv Continuations v Task Schedulers vi TaskFactory e Working with AggregateException i Flatten and Handle f Concurrent Collections i IProducerConsumerCollection ii ConcurrentBag g BlockingCollection i Writing a Producer/Consumer Queue 24 23 Span and Memory a Spans and Slicing i CopyTo and TryCopyTo ii Working with Text b Memory c Forward-Only Enumerators d Working with Stack-Allocated and Unmanaged Memory 25 24 Native and COM Interoperability a Calling into Native DLLs b Type and Parameter Marshaling i Marshaling Common Types ii Marshaling Classes and Structs iii In and Out Marshaling iv Calling Conventions c Callbacks from Unmanaged Code i Callbacks with Function Pointers (C# 9) ii Callbacks with Delegates d Simulating a C Union e Shared Memory f Mapping a Struct to Unmanaged Memory i fixed and fixed { } g COM Interoperability i The Purpose of COM ii The Basics of the COM Type System h Calling a COM Component from C# i Optional Parameters and Named Arguments ii Implicit ref Parameters iii Indexers iv Dynamic Binding i Embedding Interop Types i Type Equivalence j Exposing C# Objects to COM i Enabling Registry-Free COM 26 25 Regular Expressions a Regular Expression Basics i Compiled Regular Expressions ii RegexOptions iii Character Escapes iv Character Sets b Quantifiers i Greedy Versus Lazy Quantifiers c Zero-Width Assertions i Lookahead and Lookbehind ii Anchors iii Word Boundaries d Groups i Named Groups e Replacing and Splitting Text i MatchEvaluator Delegate ii Splitting Text f Cookbook Regular Expressions i Recipes g Regular Expressions Language Reference 27 Index