Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Programming Microsoft Visual C# 2005
Nội dung xem thử
Mô tả chi tiết
Programming Microsoft Visual C# 2005: The Language
byDonis Marshall
Microsoft Press 2006 (704 pages)
ISBN:0735621810
Offering expert guidance, hands-on programming instruction, and practical examples, this straightforward book
will help both new and experienced developers advance their proficiency in developing applications for
Microsoft Windows and the Web.
Table of Contents
Programming Microsoft Visual C# 2005—The Language
Introduction
Part I - Core Language
Chapter 1 - Introduction to Visual C# Programming
Chapter 2 - Types
Chapter 3 - Inheritance
Part II - Core Skills
Chapter 4 - Introduction to Visual Studio 2005
Chapter 5 - Arrays and Collections
Chapter 6 - Generics
Chapter 7 - Iterators
Part III - More C# Language
Chapter 8 - Delegates and Events
Chapter 9 - Exception Handling
Part IV - Debugging
Chapter 10 - Metadata and Reflection
Chapter 11 - MSIL Programming
Chapter 12 - Debugging with Visual Studio 2005
Chapter 13 - Advanced Debugging
Part V - Advanced Concepts
Chapter 14 - Memory Management
Chapter 15 - Unsafe Code
Appendix A - Operator Overloading
Index
List of Figures
List of Tables
Programming Microsoft Visual C# 2005: The Language
byDonis Marshall
Microsoft Press 2006 (704 pages)
ISBN:0735621810
Offering expert guidance, hands-on programming instruction, and practical examples, this straightforward book
will help both new and experienced developers advance their proficiency in developing applications for
Microsoft Windows and the Web.
Table of Contents
Programming Microsoft Visual C# 2005—The Language
Introduction
Part I - Core Language
Chapter 1 - Introduction to Visual C# Programming
Chapter 2 - Types
Chapter 3 - Inheritance
Part II - Core Skills
Chapter 4 - Introduction to Visual Studio 2005
Chapter 5 - Arrays and Collections
Chapter 6 - Generics
Chapter 7 - Iterators
Part III - More C# Language
Chapter 8 - Delegates and Events
Chapter 9 - Exception Handling
Part IV - Debugging
Chapter 10 - Metadata and Reflection
Chapter 11 - MSIL Programming
Chapter 12 - Debugging with Visual Studio 2005
Chapter 13 - Advanced Debugging
Part V - Advanced Concepts
Chapter 14 - Memory Management
Chapter 15 - Unsafe Code
Appendix A - Operator Overloading
Index
List of Figures
List of Tables
Back Cover
Get hands-on, expert guidance for developing with Visual C# 2005.
Get the essential, straightforward information you need to master the core capabilities of Visual C# 2005. Both new
and experienced developers get expert guidance, hands-on programming instruction, and practical examples to help
advance their proficiency in developing applications for Microsoft Windows and the Web.
Discover how to:
Refine class usage with inheritance, polymorphism, and other strategies
Implement generics to define a type-safe data structure
Work with stacks, queues, arrays, dictionaries, and other collections
Use iterators to implement and standardize enumerator patterns
Know when to catch exceptions—and handle them locally or propagate them
Interrogate metadata and facilitate late binding by using reflection
Synchronize threads with locks, events, mutexes, and other tools
Use the Microsoft Visual Studio Debugger and explore advanced debugging techniques and tools
About the Author
Donis Marshall is a trainer, a consultant and an author with 20 years of development experience and an in-depth
background on Microsoft .NET technologies. He is the author of several books, including .NET Security Programming.
Donis teaches classes on .NET programming, debugging, security, and design and architecture. In addition, he is the
president of DebugNow.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Programming Microsoft Visual C# 2005—The Language
Donis Marshall
PUBLISHED BY Microsoft Press A Division of Microsoft Corporation
One Microsoft Way Redmond, Washington 98052-6399
Copyright © 2006 by Donis Marshall
ISBN:0735621810
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by
any means without the written permission of the publisher.
Library of Congress Control Number 2005934153
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 QWT 0 9 8 7 6 5
Distributed in Canada by H.B. Fenn and Company Ltd.
A CIP catalogue record for this book is available from the British Library.
Microsoft Press books are available through booksellers and distributors worldwide. For further information
about international editions, contact your local Microsoft Corporation office or contact Microsoft Press
International directly at fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send
comments to [email protected].
Microsoft, IntelliSense, Microsoft Press, MSDN, Visual Basic, Visual C#, Visual Studio, the Visual Studio logo,
Win32, Windows, Windows CE, the Windows logo, Windows NT, and WinFX are either registered trademarks
or trademarks of Microsoft Corporation in the United States and/or other countries. Other product and
company names mentioned herein may be the trademarks of their respective owners.
The example companies, organizations, products, domain names, e-mail addresses, logos, people, places,
and events depicted herein are fictitious. No association with any real company, organization, product,
domain name, e-mail address, logo, person, place, or event is intended or should be inferred.
This book expresses the author's views and opinions. The information contained in this book is provided
without any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its
resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or
indirectly by this book.
Acquisitions Editor: Ben Ryan
Project Editor: Valerie Woolley
Technical Editor: James D. Rogers
Copy Editor: Nancy Sixsmith
Indexer: Tony Ross and Lee Ross
Body Part No. X11-50074
This book is dedicated to my father, Herbert Marshall. He was a nuclear engineer, an artist, a confidant, a
doting husband to my mother, and most of all a compassionate person. He was a giant amongst men and
touched innumerable lives. His three sons, including myself, miss him every day.
Acknowledgments
Programming Microsoft Visual C# 2005: The Language was completed with the collaboration of several
people. I am credited on the cover, but the contribution of others is no less important. I want to especially
acknowledge the contributions of Valerie Woolley, Ben Ryan, and Jim Rogers. If possible, they would also
receive cover credit. Valerie was the project manager and provided support, encouragement, patience, and
the occasional nudge when necessary. Ben, who was the acquisitions editor, had unyielding confidence in my
ability, which is greatly appreciated. Jim Rogers was the technical editor and diligently reviewed hundreds of
pages of manuscript and code. He helped assure the superb quality of the book.
I also want to thank John Bruno, who is an exceptional engineer, for reviewing and commenting on each
chapter, which was very helpful.
Writing a book is an all-consuming project. Unfortunately, much of this burden is carried by friends and loved
ones. I appreciate the patience and support of my mother, Lynn, and of my friends Herb, Jr., Chuck, and
Patty, along with a long list of other friends who were treated shabbily during this project. Thanks for your
understanding.
Finally, I want to acknowledge my children: Jason, Kristen, and Adam. They make every day special. They
are my motivation. A special acknowledgment is reserved for Jason. During most of this project, Jason was
stationed in Iraq as a Marine. He recently returned home safely. We are proud of you.
Donis Marshall
Donis Marshall is currently one of the few trainers endorsed by Microsoft Global Learning Services to conduct
Microsoft technology classes for Microsoft employees. In this capacity, Mr. Marshall travels internationally,
delivering dozens of classes to Microsoft developers and engineers in the United States, Europe, and Asia.
His repertoire includes classes on Advanced .NET UMD Debugging, Advanced .NET Debugging workshops,
.NET Design and Architecture, Visual Basic .NET Programming, .NET Interoperability and Security, .NET
Web Services, and ASP.NET. He also teaches .NET classes at Autodesk, NCCI, and NASA.
Donis Marshall is a nationally recognized teacher of computer technology to developers and scientists. As
founder and lead instructor for The Training Alliance, he taught advanced technical classes for many Fortune
500 clients. He also managed a staff of technical instructors as Director of Advanced Technical Learning
Services at Productivity Point International, a national franchiser of training services.
Mr. Marshall is President of DebugNow (www.debugnow). DebugNow offers an assortment of innovative
tools for support engineers and developers to debug and monitor Win32 and .NET applications.
As a contractor, Donis Marshall has written thousands of lines of code for various entities.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Introduction
Microsoft Visual C# 2005 includes several enhancements to earlier versions of the language. If you want to
learn the new features of the language, Programming Microsoft Visual C# 2005: The Language offers
detailed explanations of each improvement. One of the most awaited additions to the .NET environment is
generics. Other additions include anonymous methods, static classes, and new classes that affect garbage
collection. This book introduces these new features, provides context, and displays sample code.
Enhancements are not limited to the language. The Microsoft Visual Studio IDE has also been enhanced in
Visual Studio 2005. Microsoft continues to expand upon the impressive assortment of rapid application
development (RAD) tools that are available. The Exception Assistant, code snippets, and visualizers are
some of the more notable advancements, where the emphasis is on providing helpful information that
markedly increases developer productivity. This book details these and other improvements to previous
versions of Visual Studio.
A larger portion of the lifetime of an application is spent in maintenance and debugging. Efficient and effective
debugging tools and techniques can facilitate a more robust application, which reduces the need to debug.
You can also resolve problems more quickly when they inevitably occur. A managed application has a
managed veneer and an unmanaged underpinning. Debugging requires an understanding of both realms
where a managed application exists: managed and unmanaged. From a debugging context, Chapter 12
examines both realms of a managed application and helps developers understand how to effectively debug a
managed application.
Who Is This Book For?
Programming Microsoft Visual C# 2005: The Language is for developers who want a comprehensive
explanation of Visual C# 2005 or want to explore a specific aspect of the language. It is a composite of
chapters sequenced to provide a rational and complete review of the language. Each chapter is also
reviewable as an independent unit that encapsulates a specific topic.
This book targets both professional and casual developers. Practical, in-depth explanations are offered for
even the most ardent developers. Sample code is provided as a complement to the content. For casual
developers, code is often the clearest explanation of in-depth concepts. Actually, even for professional
developers, sample code is often invaluable. For this reason, this book contains reams of code examples.
Organization of This Book
Programming Microsoft Visual C# 2005: The Language is organized into five parts.
The first part, "Core Language," introduces the basic concepts of the language. Chapter 1 contains a general
overview of the language. Chapter 2 introduces types, which include classes and value types. Chapter 3
explains inheritance in C# and the related keywords, such as virtual, override, sealed, and abstract.
The second part, "Core Skills," covers the core skills required to create a C# application. Chapter 4 reviews
Visual Studio 2005, which is the central tool in developing a managed application. Chapter 5 explains arrays
and collections. It is hard to imagine a competent C# application that does not employ arrays or collections.
Chapter 6 introduces generics, which is a new feature of .NET Framework 2.0. Chapter 7 pertains to iterators
and the capability to enumerate collection-related classes.
The third part, "More C# Language," focuses on additional language features. Chapter 8 details managed
function pointers, which are represented by delegates and events in managed code. Chapter 9 explains
structured exception handling in the run time and within the C# language.
The fourth part, "Debugging," is an all-inclusive explanation of debugging managed code. The first two
chapters in this section provide an internal view of an assembly, which is critical for anyone debugging a
managed application: Chapter 10 introduces metadata and reflection; Chapter 11 is an overview of Microsoft
intermediate language (MSIL) programming. Chapter 12 discusses debugging with Visual Studio, which is the
preferred debugging environment for most developers. Finally, Chapter 13 discusses advanced debugging
using the MDbg, Windbg, and SOS debugger extensions.
The final part is "Advanced Concepts." Chapter 14 covers managed memory and garbage collection in the
managed environment. Chapter 15 explains unsafe code and direct pointer manipulation. This chapter also
discusses calling functions that are in unmanaged (native) libraries.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
System Requirements
You'll need the following hardware and software to build and run the code samples for this book:
Microsoft Windows XP with Service Pack 2, Microsoft Windows Server 2003 with Service Pack 1, or
Microsoft Windows 2000 with Service Pack 4
Microsoft Visual Studio 2005 Standard Edition or Microsoft Visual Studio 2005 Professional Edition
600 MHz Pentium or compatible processor (1 GHz Pentium recommended)
192 MB RAM (256 MB or more recommended)
Video (800 × 600 or higher resolution) monitor with at least 256 colors (1024 × 768 High Color 16-bit
recommended)
2 GB available space on installation drive; 1 GB available space on system drive. With MSDN, the hard
disk requirements are 2.8 GB and 1 GB, respectively.
CD-ROM or DVD-ROM drive
Microsoft Mouse or compatible pointing device
Technology Updates
As technologies related to this book are updated, links to additional information will be added to the Microsoft
Press Technology Updates Web page. Visit this page periodically for updates on Visual Studio 2005 and
other technologies:
http://www.microsoft.com/mspress/updates/
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Code Samples
All the code samples discussed in this book can be downloaded from the book's companion content Web
page at the following address:
http://www.microsoft.com/mspress/companion/0-7356-2181-0/
Support for This Book
Every effort has been made to ensure the accuracy of this book and the companion content. As corrections
or changes are collected, they will be added to a Microsoft Knowledge Base article. To view the list of known
corrections for this book, visit the following article:
http://support.microsoft.com/kb/905044
Microsoft Press provides support for books and companion content at the following Web site:
http://www.microsoft.com/learning/support/books/
Questions and Comments
If you have comments, questions, or ideas regarding the book or the companion content, or questions that
are not answered by visiting the previous sites, please send them to Microsoft Press via e-mail to
Or via postal mail to
Microsoft Press
Attn: Developer Series Editor
One Microsoft Way
Redmond, WA 98052-6399
Please note that Microsoft software product support is not offered through the preceding addresses.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Part I: Core Language
Chapter List
Chapter 1: Introduction to Visual C# Programming
Chapter 2: Types
Chapter 3: Inheritance
Chapter 1: Introduction to Visual C# Programming
Overview
Microsoft Visual C# 2005 is an object-oriented programming language used to develop applications targeting
the .NET environment. Programming languages are not unlike natural languages such as Spanish, Latin,
French, Chinese, or English—human languages that are written or spoken. Each natural language includes
rules that describe proper syntax and structure; we use these rules to convey cohesive thoughts and ideas. A
natural language also evolves over time, sometimes from or within a genus of other languages. Programming
languages share many of these attributes and also include rules for proper syntax and structure and often
evolve from other languages.
Acquiring proficiency in a programming language is similar to obtaining a high level of competency in a
natural language. Having acquired a level of competency in FORTRAN, Turkish, English, COBOL, Spanish,
German, C, and other languages (not necessarily in that order), I speak from experience. Languages are
languages. When you're learning a human language, your goals are literacy and being able to have a
conversation. If, as a student of French, you can sit in a Parisian café and read the menu while discussing
current events with the locals, your language skills are a fait accompli. The goal of this chapter is the same:
for you to become conversational in C#.
Learning a language typically begins with core elements of language. In English, these elements include
consonants, vowels, nouns, verbs, adjectives, phrases, and sentences. They represent the building blocks of
the language; you cannot read, write, or speak English without a fundamental understanding of these
language components. The key elements of C# are symbols and tokens, keywords, expressions, statements,
functions, and classes. Effective C# programming requires, of course, a fundamental understanding of these
elements, which this chapter will provide.
As you know, a sentence in English is more than random words terminated with a period. Likewise, in C#, a
programming statement is more than a collection of random clauses. The following English sentence and C#
statement are both nonsensical:
Programming fun is C#.
for(i<5;int i=0;++i)
In both cases, the correct elements are present, but the structure is incorrect. Using either a human language
or a programming language to convey cohesive ideas, concepts, tasks, or instructions requires organizing the
words and other elements of the language correctly. In the English language, syntax (the rules of a language)
indicates where a linking verb is placed in relation to the noun object. By comparison, C# syntax orders the
clauses of a for statement. According to C# syntax, the previous for statement should be structured like this:
for(int i=0;i<5;++i). Understanding the underlying language syntax is equally important for natural and
programming languages. This chapter will also provide the basic syntax of the C# language.
Mandarin Chinese is a tonal language, whereas English is a stress language. Learning Chinese is more than
simply assimilating new words and sentence structures. You must also learn tones because the meaning of a
Chinese word can change based on tone. Speaking Chinese with English enunciation would be confusing
and amusing at best. Similarly, C# is an object-oriented language, not a procedural language (more on this
difference later). C#, C++, Java, SmallTalk, Eiffel, and other object-oriented languages are only as effective
as your appreciation of object-oriented concepts and programming techniques. I recommend a basic
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
knowledge of object-oriented analysis and design concepts as a complement to the newly acquired C# skills
this book will give you.
Finally, languages do not emerge spontaneously. Natural languages have been evolving for nearly 150,000
years, and knowing the heritage of and the influences on a language can be informative and helpful. For
example, English, French, German, Yiddish, and related languages are heavily influenced by their Latin
language heritage. As such, they have common words, syntax, and structures that are characteristic of the
Latin metalanguage. The origin of C# does not date back centuries, but an understanding of its evolution is
invaluable.
Language Origin
From the time when the first natural language appeared, hundreds of thousands of languages have
emerged. Many of these languages are now extinct, leaving about six thousand languages that are currently
spoken. Some of these languages are similar and grouped by classification. Other languages are quite
distinct, such as Kora, which incorporates a series of click sounds and is spoken by bushmen in Africa.
A list of programming languages is modest when compared with the catalogue of natural languages.
Beginning in the 1940s with Plankalkül, more than 1,000 programming languages have been documented.
Like natural languages, the variety and diversity of these languages is impressive: the succinctness of
assembler, the verbosity of COBOL, and the efficiency of C. For a comprehensive list of programming
languages, visit this link: http://oop.rosweb.ru/Other/.
The motivations that inspire the creation of languages are diverse: FORTRAN was created for scientific
analysis, COBOL for building business applications, RPG for report generation, and so on. Some languages
serve as refinements of earlier languages. CPL combined the best ingredients of several languages,
including ALGOL, FORTRAN, and COBOL. C# is an independently developed, object-oriented language and
a member of the C family of languages. It shares similar syntax and some concepts with other C-family
languages; more important, however, C# has few if any vestiges of procedural programming, in which the
basic programming element is the procedure (that is, a named sequence of statements, such as a routine,
subroutine, or function). Unfortunately, C++ inherited many of the artifacts of procedural programming from
C. C#, however, was designed to be a purely object-oriented language.
ALGOL is arguably the most influential programming language in history. The language was introduced in
1958 but became popular when ALGOL-60 was released in 1960. ALGOL quickly became the dominant
language in Europe during the 1960s. Its impact on future languages such as Pascal, C, and Java is
undeniable—these languages' grammatical syntax borrows heavily from ALGOL. I've programmed
professionally in ALGOL, assembler, COBOL, FORTRAN, C, C++, C#, Basic (in various renditions), Forth,
JavaScript, HTML, XML, MISL, and many more—and ALGOL remains my favorite language. The major
design goals of ALGOL were portability, a formal grammar, and support for algorithms. ALGOL-68 extended
the language, but the additions increased complexity and furthered abstraction from hardware. This
abstraction prevented developers from easily accessing devices and the lower tiers of the operating
environment. Soon, languages were introduced that were less complex and not as abstracted from the
architecture. One of these new languages was C.
The journey from ALGOL to C began with CPL. CPL, a derivative of ALGOL-60, was developed at the
Computer Lab of Cambridge University. CPL was created in 1963 by David Barron, Christopher Strachey,
and Martin Richards. Although CPL is not as abstracted as ALGOL, it did maintain one characteristic of
ALGOL: complexity. Martin Richards introduced Basic CPL (BCPL) in 1967 as a lean version of CPL. Ken
Thompson of Bell Labs drafted B in 1970 as the successor to BCPL. B was lighter, faster, and more
appropriate for systems programming. C was developed by Dennis Ritchie, also of Bell Labs, in 1972. C
returned some of the abstraction removed from B while keeping that language simple and quick. Although
initially consigned to the UNIX operation system and systems programming, C is a general-purpose language
and has been used for a diverse assortment of applications across a variety of platforms and operating
systems.
FORTAN, ALGOL, and COBOL dominated the procedural programming landscape in the 1960s. On a
separate track, Simula was created between 1962 and 1965 by Ole-Johan Dahl and Kristen Nygaard at the
Norwegian Computing Center. Simula is notable for being the first object-oriented programming (OOP)
language. It was designed for simulation, but evolved into a general-purpose language. Simula introduced the
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
important OOP concepts of classes, inheritance, and dynamic binding.
Combining aspects of C and Simula, Bjarne Stroustrup introduced C with Classes in 1979 as an
enhancement of the C programming language. Later, under Stroustrup's stewardship, C++ was created as a
direct descendant of C with Classes and was publicly recognized in 1983. C++ rapidly became the premier
object-oriented programming language and introduced structured exception handling, templates, and much
more.
C# premiered at the Professional Developers Conference (PDC) held in Orlando, Florida, in 2000. The
primary architects of C# were Anders Hejlsberg, Scott Wiltamuth, Peter Sollichy, Eric Gunnerson, and Peter
Golde. C# was designed to be a fully object-oriented language focusing on developing components in a
distributed environment and was launched as part of a larger initiative by Microsoft called Microsoft .NET.
Underscoring the importance of .NET to Microsoft, Bill Gates was the keynote speaker at the PDC that year. I
attended the PDC in 2000 and was both intrigued and motivated by the introduction of .NET and C#. .NET is
emblematic of a philosophical change at Microsoft and an embracing of the standards community.
Both .NET, as defined by the Common Language Infrastructure (CLI), and C# were submitted to two
international standards organizations: ECMA and ISO/IEC. Also, .NET and .NET languages, described in the
Common Language Specification (CLS), continue the trend toward truly portable code. You can write an
application in one environment and run it anywhere else. Simultaneously, a new version of Microsoft Visual
Studio was announced: Visual Studio .NET. Visual Studio .NET provides rapid application development tools
for developing a wide variety of .NET applications.
More Info For information on the various standards for C# and .NET, follow these links. The current
ECMA standards for the C# Language Specification:http://www.ecmainternational.org/publications/standards/Ecma-334.htm. The current ECMA standards for
the Common Language Infrastructure: http://www.ecmainternational.org/publications/standards/Ecma-335.htm. The current ISO/IEC standards for
the C# Language Specification:
http://www.iso.org/iso/en/CatalogueDetailPage.CatalogueDetail?
CSNUMBER=36768&ICS1=35&ICS2=60&ICS3=. The current ISO/IEC standards for the
CLI: http://www.iso.org/iso/en/CatalogueDetailPage.CatalogueDetail?
CSNUMBER=36769&scopelist=.