1058 illustrated c 2012, 4th edition

750 63 0
1058 illustrated c 2012, 4th edition

Đ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

www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them www.it-ebooks.info Contents at a Glance  About the Author xxvii  About the Technical Reviewer xxviii  Acknowledgments xxix  Introduction xxx  Chapter 1: C# and the NET Framework  Chapter 2: Overview of C# Programming .15  Chapter 3: Types, Storage, and Variables 33  Chapter 4: Classes: The Basics 49  Chapter 5: Methods 67  Chapter 6: More About Classes 113  Chapter 7: Classes and Inheritance 159  Chapter 8: Expressions and Operators .201  Chapter 9: Statements 239  Chapter 10: Structs 269  Chapter 11: Enumerations 279  Chapter 12: Arrays 293  Chapter 13: Delegates .323  Chapter 14: Events 347  Chapter 15: Interfaces 363  Chapter 16: Conversions 391  Chapter 17: Generics 421  Chapter 18: Enumerators and Iterators 461  Chapter 19: Introduction to LINQ 483 iv www.it-ebooks.info  Chapter 20: Introduction to Asynchronous Programming 541  Chapter 21: Namespaces and Assemblies 603  Chapter 22: Exceptions .631  Chapter 23: Preprocessor Directives 651  Chapter 24: Reflection and Attributes 663  Chapter 25: Other Topics 691  Index 719 v www.it-ebooks.info Introduction The purpose of this book is to teach you the syntax and semantics of the C# programming language in as clear a manner as possible C# is a wonderful programming language! I love coding in it I don’t know how many programming languages I’ve learned over the years, but C# is by far my favorite I hope that by using this book, you can gain an appreciation for C#’s beauty and elegance Most books teach programming primarily using text That’s great for novels, but many of the important concepts of programming languages can best be understood through a combination of words, figures, and tables Many of us think visually, and figures and tables can help clarify and crystallize our understanding of a concept In several years of teaching programming languages, I have found that the pictures I drew on the whiteboards were the things that most quickly helped the students understand the concepts I was trying to convey Illustrations alone, however, are not sufficient to explain a programming language and platform The goal of this book is to find the best combination of words and illustrations to give you a thorough understanding of the language, and to allow the book to serve as a reference resource as well This book is written for anyone who wants an introduction to the C# programming language— from the novice to the seasoned programmer For those just getting started in programming, I've included the basics For seasoned programmers, the content is laid out succinctly, and in a form that allows you to go directly to the information required without having to wade through oceans of words For both sets of programmers, the content itself is presented graphically, in a form that should make the language easy to learn Enjoy! Audience, Source Code, and Contact Information This book was written for beginning and intermediate programmers, and programmers coming from another language such as Visual Basic or Java I have tried to remain focused on the C# language itself, and give an in-depth description of the language and all its parts, rather than straying off into coverage of NET or programming practices I wanted to keep this book as succinct as I could while still covering the language thoroughly—and there are other good books covering these other topics You can download the source code for all the example programs from the Apress web site or from the web site for this book, which is www.illustratedcsharp.com And although I can’t answer specific questions about your code, you can contact me with suggestions and feedback about the book at dansolis@sbcglobal.net I hope this book helps making learning C# an enjoyable experience for you! Take care Dan Solis xxx www.it-ebooks.info CHAPTER C# and the NET Framework  Before NET  Enter Microsoft NET  Compiling to the Common Intermediate Language  Compiling to Native Code and Execution  The Common Language Runtime  The Common Language Infrastructure  Review of the Acronyms  The Evolution of C# www.it-ebooks.info CHAPTER  C# AND THE NET FRAMEWORK Before NET The C# programming language was designed for developing programs for Microsoft’s NET Framework This chapter gives a brief look at where NET came from and its basic architecture To start off, let’s get the name right: C# is pronounced “see sharp.”1 Windows Programming in the Late 1990s In the late 1990s, Windows programming using the Microsoft platform had fractured into a number of branches Most programmers were using Visual Basic, C, or C++ Some C and C++ programmers were using the raw Win32 API, but most were using Microsoft Foundation Classes (MFC) Others had moved to the Component Object Model (COM) All these technologies had their own problems The raw Win32 API was not object-oriented, and using it required a lot more work than MFC MFC was object-oriented but was inconsistent and getting old COM, although conceptually simple, was complex in its actual coding and required lots of ugly, inelegant plumbing Another shortcoming of all these programming technologies was that they were aimed primarily at developing code for the desktop rather than the Internet At the time, programming for the Web was an afterthought and seemed very different from coding for the desktop Goals for the Next-Generation Platform Services What we really needed was a new start—an integrated, object-oriented development framework that would bring consistency and elegance back to programming To meet this need, Microsoft set out to develop a code execution environment and a code development environment that met these goals Figure 1-1 lists these goals Figure 1-1 Goals for the next-generation platform Enter Microsoft NET In 2002, Microsoft released the first version of the NET Framework, which promised to address the old problems and meet the goals for the next-generation systems The NET Framework is a much more I was once interviewed for a contract C# position when the Human Resources interviewer asked me how much experience I’d had programming in “see pound” (instead of “see sharp”)! It took me a moment to realize what he was talking about www.it-ebooks.info CHAPTER  C# AND THE NET FRAMEWORK consistent and object-oriented environment than either the MFC or COM programming technologies Some of its features include the following: • Multiple platforms: The system runs on a broad range of computers, from servers and desktop machines to PDAs and cell phones • Industry standards: The system uses industry-standard communication protocols, such as XML, HTTP, SOAP, JSON, and WSDL • Security: The system can provide a much safer execution environment, even in the presence of code obtained from suspect sources Components of the NET Framework The NET Framework consists of three components, as shown in Figure 1-2 The execution environment is called the Common Language Runtime (CLR) The CLR manages program execution at run time, including the following: • Memory management and garbage collection • Code safety verification • Code execution, thread management, and exception handling The programming tools include everything you need for coding and debugging, including the following: • The Visual Studio integrated development environment (IDE) • NET-compliant compilers (e.g., C#, Visual Basic NET, F#, IronRuby, and managed C++) • Debuggers • Web development server-side technologies, such as ASP.NET and WCF The Base Class Library (BCL) is a large class library used by the NET Framework and available for you to use in your programs as well Figure 1-2 Components of the NET Framework www.it-ebooks.info CHAPTER  C# AND THE NET FRAMEWORK An Improved Programming Environment The NET Framework offers programmers considerable improvements over previous Windows programming environments The following sections give a brief overview of its features and their benefits Object-Oriented Development Environment The CLR, the BCL, and C# are designed to be thoroughly object-oriented and act as a well-integrated environment The system provides a consistent, object-oriented model of programming for both local programs and distributed systems It also provides a software development interface for desktop application programming, mobile application programming, and web development, consistent across a broad range of targets, from servers to cell phones Automatic Garbage Collection The CLR has a service called the garbage collector (GC), which automatically manages memory for you • The GC automatically removes objects from memory that your program will no longer access The GC relieves programmers of tasks they have traditionally had to perform, such as deallocating memory and hunting for memory leaks This is a huge improvement, since hunting for memory leaks can be difficult and time-consuming Interoperability The NET Framework was designed for interoperability between different NET languages, the operating system or Win32 DLLs, and COM • The NET language interoperability allows software modules written using different NET languages to interact seamlessly − A program written in one NET language can use and even inherit from a class written in another NET language, as long as certain rules are followed − Because of its ability to easily integrate modules produced in different programming languages, the NET Framework is sometimes described as language-agnostic www.it-ebooks.info CHAPTER  C# AND THE NET FRAMEWORK • The NET Framework provides a feature called platform invoke (P/Invoke), which allows code written for NET to call and use code not written for NET It can use raw C functions imported from standard Win32 DLLs, such as the Windows APIs • The NET Framework also allows interoperability with COM .NET Framework software components can call COM components, and COM components can call NET components as if they were COM components themselves No COM Required The NET Framework frees the programmer from the COM legacy If you’re coming from a COM programming environment you’ll be happy to know that, as a C# programmer, you don’t need to use any of the following: • The IUnknown interface: In COM, all objects must implement interface IUnknown In contrast, all NET objects derive from a single class called object Interface programming is still an important part of NET, but it’s no longer the central theme • Type libraries: In COM, type information is kept in type libraries as tlb files, which are separate from the executable code In NET, a program’s type information is kept bundled with the code in the program file • Manual reference counting: In COM, the programmer had to keep track of the number of references to an object to make sure it wasn’t deleted at the wrong time In NET, the GC keeps track of references and removes objects only when appropriate • HRESULT: COM used the HRESULT data type to return runtime error codes .NET doesn’t use HRESULTs Instead, all unexpected runtime errors produce exceptions • The registry: COM applications had to be registered in the system registry, which holds information about the configurations of the operating system and applications .NET applications don’t need to use the registry This simplifies the installation and removal of programs (However, there is something similar called the global assembly cache, which I’ll cover in Chapter 21.) Although the amount of COM code that’s currently being written is fairly small, there’s still quite a number of COM components in systems currently being used, and C# programmers sometimes need to write code that interfaces with those components C# 4.0 introduced several new features that make that task easier These features are covered in Chapter 25 www.it-ebooks.info  CONTENTS Another Form of the using Statement 266 Other Statements 267  Chapter 10: Structs 269 What Are Structs? 270 Structs Are Value Types .271 Assigning to a Struct .272 Constructors and Destructors 273 Instance Constructors 273 Static Constructors 275 Summary of Constructors and Destructors 275 Field Initializers Are Not Allowed 276 Structs Are Sealed 276 Boxing and Unboxing .276 Structs As Return Values and Parameters 277 Additional Information About Structs 277  Chapter 11: Enumerations 279 Enumerations .280 Setting the Underlying Type and Explicit Values 282 Implicit Member Numbering 283 Bit Flags .284 The Flags Attribute 286 Example Using Bit Flags 288 More About Enums 290  Chapter 12: Arrays 293 Arrays 294 Definitions 294 xv www.it-ebooks.info  CONTENTS Important Details 294 Types of Arrays 295 An Array As an Object 296 One-Dimensional and Rectangular Arrays 297 Declaring a One-Dimensional or Rectangular Array 297 Instantiating a One-Dimensional or Rectangular Array 298 Accessing Array Elements .299 Initializing an Array 300 Explicit Initialization of One-Dimensional Arrays 300 Explicit Initialization of Rectangular Arrays 301 Syntax Points for Initializing Rectangular Arrays 301 Shortcut Syntax 302 Implicitly Typed Arrays 303 Putting It All Together 304 Jagged Arrays 305 Declaring a Jagged Array 306 Shortcut Instantiation 306 Instantiating a Jagged Array 307 Subarrays in Jagged Arrays 308 Comparing Rectangular and Jagged Arrays 310 The foreach Statement 311 The Iteration Variable Is Read-Only 313 The foreach Statement with Multidimensional Arrays 314 Array Covariance 316 Useful Inherited Array Members 317 The Clone Method 319 Comparing Array Types 321 xvi www.it-ebooks.info  CONTENTS  Chapter 13: Delegates .323 What Is a Delegate? .324 An Overview of Delegates 326 Declaring the Delegate Type 328 Creating the Delegate Object .329 Assigning Delegates 331 Combining Delegates 332 Adding Methods to Delegates 333 Removing Methods from a Delegate .334 Invoking a Delegate .335 Delegate Example 336 Invoking Delegates with Return Values 337 Invoking Delegates with Reference Parameters 338 Anonymous Methods .339 Using Anonymous Methods 340 Syntax of Anonymous Methods 340 Scope of Variables and Parameters 342 Lambda Expressions 344  Chapter 14: Events 347 Publishers and Subscribers 348 Overview of Source Code Components 350 Declaring an Event .351 An Event Is a Member 352 Subscribing to an Event .353 Raising an Event 354 Standard Event Usage 356 xvii www.it-ebooks.info  CONTENTS Passing Data by Extending EventArgs 358 Removing Event Handlers 360 Event Accessors 362  Chapter 15: Interfaces 363 What Is an Interface? 364 Example Using the IComparable Interface 366 Declaring an Interface 370 Implementing an Interface 372 Example with a Simple Interface 373 An Interface Is a Reference Type 374 Using the as Operator with Interfaces 376 Implementing Multiple Interfaces 377 Implementing Interfaces with Duplicate Members 378 References to Multiple Interfaces 380 An Inherited Member As an Implementation 382 Explicit Interface Member Implementations 383 Accessing Explicit Interface Member Implementations 386 Interfaces Can Inherit Interfaces 387 Example of Different Classes Implementing an Interface 388  Chapter 16: Conversions 391 What Are Conversions? 392 Implicit Conversions 393 Explicit Conversions and Casting 394 Casting 395 Types of Conversions 396 Numeric Conversions 396 xviii www.it-ebooks.info  CONTENTS Implicit Numeric Conversions 397 Overflow Checking Context 398 Explicit Numeric Conversions 400 Reference Conversions 404 Implicit Reference Conversions 405 Explicit Reference Conversions 407 Valid Explicit Reference Conversions 408 Boxing Conversions .409 Boxing Creates a Copy 410 The Boxing Conversions 411 Unboxing Conversions 411 The Unboxing Conversions 412 User-Defined Conversions .413 Constraints on User-Defined Conversions 413 Example of a User-Defined Conversion 414 Evaluating User-Defined Conversions 416 Example of a Multistep User-Defined Conversion 416 The is Operator 418 The as Operator .419  Chapter 17: Generics 421 What Are Generics? .422 A Stack Example 422 Generics in C# 424 Continuing with the Stack Example 425 Generic Classes .426 Declaring a Generic Class 427 Creating a Constructed Type 428 xix www.it-ebooks.info  CONTENTS Creating Variables and Instances 429 The Stack Example Using Generics 431 Comparing the Generic and Nongeneric Stack 433 Constraints on Type Parameters 434 Where Clauses 435 Constraint Types and Order 436 Generic Methods 438 Declaring a Generic Method 439 Invoking a Generic Method 440 Example of a Generic Method 442 Extension Methods with Generic Classes 443 Generic Structs 444 Generic Delegates 445 Another Generic Delegate Example 447 Generic Interfaces 448 An Example Using Generic Interfaces 449 Generic Interface Implementations Must Be Unique 450 Covariance 451 Contravariance .455 Covariance and Contravariance in Interfaces 458 More About Variance 460  Chapter 18: Enumerators and Iterators 461 Enumerators and Enumerable Types 462 Using the foreach Statement 462 The IEnumerator Interface .464 Example Using IEnumerable and IEnumerator 468 The Generic Enumeration Interfaces .470 xx www.it-ebooks.info  CONTENTS Iterators 472 Iterator Blocks 473 Using an Iterator to Create an Enumerator 474 Using an Iterator to Create an Enumerable 476 Common Iterator Patterns .478 Producing Multiple Enumerables 479 Iterators As Properties 480 Behind the Scenes with Iterators 482  Chapter 19: Introduction to LINQ 483 What Is LINQ? 484 LINQ Providers .485 Anonymous Types 486 Method Syntax and Query Syntax 488 Query Variables 490 The Structure of Query Expressions 491 The from Clause 492 The join Clause 494 What Is a Join? 495 The from let where Section in the Query Body 498 The orderby Clause 502 The select group Clause 503 Anonymous Types in Queries 505 The group Clause 506 Query Continuation: The into Clause 508 The Standard Query Operators 509 Signatures of the Standard Query Operators 513 Query Expressions and the Standard Query Operators 515 xxi www.it-ebooks.info  CONTENTS Delegates As Parameters 516 The LINQ Predefined Delegate Types 517 Example Using a Delegate Parameter 518 Example Using a Lambda Expression Parameter 519 LINQ to XML 521 Markup Languages 521 XML Basics 522 The XML Classes 524 Working with XML Attributes 532 Other Types of Nodes 536 Using LINQ Queries with LINQ to XML 538  Chapter 20: Introduction to Asynchronous Programming 541 What Is Asynchrony? .542 A Starting Example 543 The Structure of the async/await Feature .547 What Is An async Method? 548 The Flow of Control in an Async Method 552 The await Expression 555 Cancelling an async Operation 560 Exception Handling and the await Expression 562 Waiting Synchronously for Tasks in the Calling Method 563 Waiting Asynchronously for Tasks in the async Method 567 The Task.Delay Method 569 Async Operations in GUI Programs 571 Task.Yield 574 Using an async Lambda Expression 575 A Full GUI Example .577 xxii www.it-ebooks.info  CONTENTS The BackgroundWorker Class 579 Example of the BackgroundWorker Class in a WPF Program 583 Parallel Loops 586 Other Asynchronous Programming Patterns 589 BeginInvoke and EndInvoke 591 The Wait-Until-Done Pattern 593 The AsyncResult Class 594 The Polling Pattern 595 The Callback Pattern 597 Timers 600  Chapter 21: Namespaces and Assemblies 603 Referencing Other Assemblies 604 The mscorlib Library 606 Namespaces 608 Namespace Names 612 More About Namespaces 613 Namespaces Spread Across Files 614 Nesting Namespaces 615 The using Directives 616 The using Namespace Directive 616 The using Alias Directive 617 The Structure of an Assembly .618 The Identity of an Assembly 620 Strongly Named Assemblies 622 Creating a Strongly Named Assembly 623 Private Deployment of an Assembly 624 Shared Assemblies and the GAC 625 xxiii www.it-ebooks.info  CONTENTS Installing Assemblies into the GAC 625 Side-by-Side Execution in the GAC 626 Configuration Files .627 Delayed Signing 628  Chapter 22: Exceptions .631 What Are Exceptions? 632 The try Statement 633 Handling the Exception 634 The Exception Classes 635 The catch Clause 637 Examples Using Specific catch Clauses 638 The catch Clauses Section 639 The finally Block 640 Finding a Handler for an Exception 641 Searching Further 642 General Algorithm 643 Example of Searching Down the Call Stack 644 Throwing Exceptions .647 Throwing Without an Exception Object 648  Chapter 23: Preprocessor Directives 651 What Are Preprocessor Directives? .652 General Rules .652 The #define and #undef Directives 654 Conditional Compilation .655 The Conditional Compilation Constructs 656 Diagnostic Directives .659 xxiv www.it-ebooks.info  CONTENTS Line Number Directives 660 Region Directives 661 The #pragma warning Directive 662  Chapter 24: Reflection and Attributes 663 Metadata and Reflection 664 The Type Class .664 Getting a Type Object 666 What Is an Attribute? .669 Applying an Attribute .670 Predefined, Reserved Attributes 671 The Obsolete Attribute 671 The Conditional Attribute 672 The Caller Information Attributes 674 The DebuggerStepThrough Attribute 675 Other Predefined Attributes 676 More About Applying Attributes 677 Multiple Attributes 677 Other Types of Targets 678 Global Attributes 679 Custom Attributes 680 Declaring a Custom Attribute 680 Using Attribute Constructors 681 Specifying the Constructor 681 Using the Constructor 682 Positional and Named Parameters in Constructors 683 Restricting the Usage of an Attribute 684 Suggested Practices for Custom Attributes 686 xxv www.it-ebooks.info  CONTENTS Accessing an Attribute 687 Using the IsDefined Method 687 Using the GetCustomAttributes Method 688  Chapter 25: Other Topics 691 Overview 692 Strings 692 The StringBuilder Class 694 Parsing Strings to Data Values 695 More About the Nullable Types 697 Assigning to a Nullable Type 699 The Null Coalescing Operator 700 Using Nullable User-Defined Types 701 Method Main 703 Accessibility of Main 704 Documentation Comments 705 Inserting Documentation Comments 706 Using Other XML Tags 707 Nested Types 708 Example of a Nested Class 708 Visibility and Nested Types 710 Destructors and the Dispose Pattern 712 The Standard Dispose Pattern 713 Comparing Constructors and Destructors 715 Interoperating with COM 716  Index 719 xxvi www.it-ebooks.info About the Author  Dan Solis holds a Bachelor of Arts degree with majors in biology and English He initially worked in research on the structure of bi- and trimetal crystals, until he found that he enjoyed programming much more than working in a lab He also holds a Master of Science degree in computer science from the University of California at Santa Barbara, where he concentrated on programming languages and compiler design Dan has been programming professionally for more than 20 years, with more than half that time working as a consultant and contract programmer, including several projects for Microsoft Consulting Services His consulting projects have ranged from programs for mutual fund analysis and supply chain management to systems for missile tracking He has also taught courses on various programming languages, Windows programming, UNIX internals, and a number of other topics, in both the United States and Europe Dan’s first programming language was C, but he soon became intrigued by the journal articles about a new language being developed called “C with Classes.” Eventually that language was renamed C++ and released to the world He began using C++ as soon as he could get access to a compiler, and he eventually started teaching training seminars on the language, as well as continuing to code With the advent of C#, NET, and WPF, he has moved on to enjoying the myriad advantages of the new platform and has been working with them enthusiastically ever since xxvii www.it-ebooks.info About the Technical Reviewer  Aleksandar Lukic is a software architect specializing in Microsoft technologies He has built and designed systems for a wide variety of industries, including e-commerce, cosmetics, and energy He also spent four years as a Microsoft ASP.NET MVP, delivering support to the NET community You can contact Aleksandar via his blog, at blogs.developpeur.org/Aleks xxviii www.it-ebooks.info Acknowledgments I want to thank Sian for supporting and encouraging me on a daily basis, and I want to thank my parents and brothers and sisters for their continued love and support I also want to express my gratitude to the people at Apress who have worked with me to bring this book to fruition I really appreciate that they understood and appreciated what I was trying to and worked with me to achieve it Thanks to all of you xxix www.it-ebooks.info ... OVERVIEW OF C# PROGRAMMING A Simple C# Program This chapter lays the groundwork for studying C# Since I’ll use code samples extensively throughout the text, I first need to show you what a C# program... Figure 1-9 The focuses of the feature sets for the releases of C# 14 www.it-ebooks.info CHAPTER Overview of C# Programming  A Simple C# Program  Identifiers  Keywords  Main: The Starting Point... Infrastructure  Review of the Acronyms  The Evolution of C# www.it-ebooks.info CHAPTER  C# AND THE NET FRAMEWORK Before NET The C# programming language was designed for developing programs

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

Từ khóa liên quan

Mục lục

  • C# and the .NET Framework

    • Before .NET

      • Windows Programming in the Late 1990s

      • Goals for the Next-Generation Platform Services

      • Enter Microsoft .NET

        • Components of the .NET Framework

        • An Improved Programming Environment

          • Object-Oriented Development Environment

          • Automatic Garbage Collection

          • Interoperability

          • No COM Required

          • Simplified Deployment

          • Type Safety

          • The Base Class Library

          • Compiling to the Common Intermediate Language

          • Compiling to Native Code and Execution

            • Overview of Compilation and Execution

            • The Common Language Runtime

            • The Common Language Infrastructure

              • Important Parts of the CLI

                • The Common Type System

                • The Common Language Specification

                • Review of the Acronyms

                • The Evolution of C#

                • Overview of C# Programming

                  • A Simple C# Program

                    • More About SimpleProgram

                    • Identifiers

                    • Keywords

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan