1. Trang chủ
  2. » Khoa Học Tự Nhiên

2006 aw essential c sharp v2 0

1,1K 54 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.100
Dung lượng 6,01 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Masterfully organized, it allows beginning programmers to get on board and leads more experienced programmers into the world of structured programming.. For programmers who want to solve

Trang 1

By Mark Michaelis

Publisher: Addison Wesley Professional Pub Date: July 13, 2006

Print ISBN-10: 0321150775 Print ISBN-13: 978-0-321-15077-6 Pages: 768

to build their next generation of applications." Stephen Toub, technical editor, MSDN

Magazine

"This book provides complete, up-to-date coverage of all the programming constructs in C# Masterfully organized, it allows beginning programmers to get on board and leads more experienced programmers into the world of structured programming Because of its unwavering focus on the essential programming constructs of C#such as generics,

delegates, and much morethis book is indispensable For programmers who want to solve their day-to-day programming issues using the latest features this modern programming

language has to offer, this book is indispensable." Narendra Poflee, IT integration

specialist, Itron Inc.

"Essential C# 2.0 is an ideal book for all programmers interested in C# If you are a

beginner, you will quickly learn the basics of C# programming and become familiar with the concepts The flow of the text is easy to follow and does a great job of not repeating concepts that have already been covered For the experienced programmer, this book has priceless nuggets embedded within its pages, making it a great read for programmers who are already familiar with C# This will be a book that I will keep next to my computer for

years to come." Michael Stokesbary, software engineer, Itron Inc.

Essential C# 2.0 is a clear, concise guide to C#including the features new to C# 2.0 The

Trang 2

comparisons between C# and other languages The C# language is covered

comprehensively and each important construct is illustrated with succinct code examples Complete code examples are available online Mark Michaelis has organized the material for quick access Graphical "mind maps" at the beginning of each chapter show what material is covered and how each topic relates to the whole.

Following the C# introduction, readers will learn about

C# primitive data types, value types, reference types, type conversions, and arrays Operators and control flow, loops, conditional logic, and sequential programming Methods, parameters, exception handling, and structured programming

separate appendix on C# 2.0 topics helps readers quickly find new features of the

language.

Whether you're just starting out as a programmer, are an experienced developer looking to learn C#, or are a seasoned C# programmer interested in learning the new features of C#

2.0, Essential C# 2.0 gives you just what you need to quickly get up and running writing

C# applications.

Trang 3

By Mark Michaelis

Publisher: Addison Wesley Professional Pub Date: July 13, 2006

Print ISBN-10: 0321150775 Print ISBN-13: 978-0-321-15077-6 Pages: 768

Trang 8

Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and the publisher wasaware of a trademark claim, the designations have been printedwith initial capital letters or in all capitals

The NET logo is either a registered trademark or trademark ofMicrosoft Corporation in the United States and/or other

countries and is used under license from Microsoft

The author and publisher have taken care in the preparation ofthis book, but make no expressed or implied warranty of anykind and assume no responsibility for errors or omissions Noliability is assumed for incidental or consequential damages inconnection with or arising out of the use of the information orprograms contained herein

The publisher offers excellent discounts on this book when

ordered in quantity for bulk purchases or special sales, whichmay include electronic versions and/or custom covers and

content particular to your business, training goals, marketingfocus, and branding interests For more information, please

Trang 9

photocopying, recording, or likewise For information regardingpermissions, write to:

Dedication

Trang 10

to write effective applications and managed code Learn fromthe leaders how to maximize your use of the NET Frameworkand its programming languages.

Trang 14

"Essential C# 2.0 pulls off a very difficult task The early

chapters are comprehensible by beginning developers,while the later chapters pull no punches and provide theexperienced developer with the detailed information theyneed to make the most of C# 2.0 Starting with the firstchapter, Mark has successfully interwoven tidbits of

information useful to even the most advanced developerwhile keeping the book approachable."

Chris Kinsman, chief architect, Vertafore, Microsoft

Regional Director

"How refreshing! This book deals with C# thoroughly,rather than skimming over the whole NET framework It

is valuable to newcomers and professionals alike."

Jon Skeet, C# MVP

"Essential C# 2.0 is a one-stop shop for an experienced

programmer looking to ramp up on one of the hottestlanguages around today Mark delivers an intelligent anddetailed tour of C#, providing newcomers to the languagewith a solid foundation of skill on which to build their nextgeneration of applications."

Stephen Toub, technical editor, MSDN Magazine

"This book provides complete, up-to-date coverage of allthe programming constructs in C# Masterfully organized,

it allows beginning programmers to get on board and

leads more experienced programmers into the world ofstructured programming Because of its unwavering focus

on the essential programming constructs of C#such as

Trang 15

indispensable For programmers who want to solve their

day-to-day programming issues using the latest featuresthis modern programming language has to offer, this book

and does a great job of not repeating concepts that havealready been covered For the experienced programmer,

programming (C++), ubiquity across platforms (Java), and

highly structured models that form the basis of C#, it is clearthat the language is well positioned to hold its own as a

dominant development language

This book has everything a developer needs to know to get upand running with the language Many concise code samples, theuse of mind maps to provide context, and the interesting way

Mark contrasts C# with other languages make Essential C# 2.0

stand out in a sea of C# books

I have known Mark for a while now His extensive involvement

Trang 16

experience as an author of books on C++, COM+, and C#,

uniquely qualify him to write the book that I believe will be aseminal reference for C#

Further, Mark's teaching experience allows him to combine theworld of technical skill with that of practical, intuitive tutorial Itbegins with principles of object programming in C#, as it is areference to verify advanced multithreading techniques in acomplex system The reader, novice or expert, will enjoy hiscasual style and method of eloquently communicating

challenging topics

This reference and tutorial should be on the shelf next to yourworkstation and carried in your backpack Pick it up and read it!

Im confident that whether you are new or experienced with thelanguage, you will learn something in this book that will induce

complexity This book takes you through these same paradigmshifts

The beginning chapters take you through sequential

programming structure in which statements are written in

the order in which they are executed The problem with this

Trang 17

programming, and eventually rudimentary forms of declarativeprogramming (in Chapter 14) via attributes

This book has three main functions

It provides comprehensive coverage of the C# language,going beyond a tutorial and offering a foundation upon

which you can begin effective software development

projects

For readers already familiar with C#, this book providesinsight into some of the more complex programming

paradigms and provides in-depth coverage of the featuresintroduced in the latest version of the language, C# 2.0

It serves as a timeless reference, even after you gain

proficiency with the language

The key to successfully learning C# is to start coding as soon aspossible Don't wait until you are an "expert" in theory; startwriting software immediately As a believer in iterative

development, I hope this book enables even a novice

programmer to begin writing basic C# code by the end of

A number of topics are not covered in this book You won't find

Trang 18

development, distributed programming, and so on Althoughthese topics are relevant to the NET framework, to do themjustice requires books of their own Fortunately, Addison-

Wesley's Microsoft NET Development Series provides a wealth

of writing on these topics Reading this book will prepare you tofocus on and develop expertise in any of these areas It focuses

programming practices that will serve you throughout yourprogramming career

Structured programmers: Just as it's best to learn a foreign

language through immersion, learning a computer language

is most effective when you begin using it before you knowall the intricacies In this vein, the book begins with a

tutorial that will be comfortable for those familiar with

structured programming, and by the end of Chapter 4,

developers in this category should feel at home writing

basic control flow programs However, the key to excellence

Trang 19

introduce classes and object-oriented development The role

of historically structured programming languages such as C,COBOL, and FORTRAN is still significant but shrinking, so itbehooves software engineers to become familiar with

object-oriented development C# is an ideal language formaking this transition because it was designed with object-oriented development as one of its core tenets

Object-based and object-oriented developers: C++ and

Java programmers, and many experienced Visual Basic

programmers, fall into this category Many of you are

already completely comfortable with semicolons and curlybraces A brief glance at the code in Chapter 1 reveals that

at its core, C# is similar to the C and C++ style languagesthat you already know

C# professionals: For those already versed in C#, this book

provides a convenient reference for less frequently

encountered syntax Furthermore, it provides answers tolanguage details and subtleties seldom addressed Most

importantly, it presents the guidelines and patterns for

programming robust and maintainable code This book alsoaids in the task of teaching C# to others

With the emergence of C# 2.0, some of the most prominentenhancements are:

- Partial classes (see Chapter 5)

- Global namespace qualifiers (see Chapter 9)

- Different access modifiers on property getters and

setters (see Chapter 5

Trang 20

- Generics (see Chapter 11)

- Iterator topics (see Chapter 12)

These topics are covered in detail for those not alreadyfamiliar with them Also pertinent to advanced C#

development is the subject of pointers, in Chapter 17 Evenexperienced C# developers often do not understand thistopic well

Features of This Book

Essential C# 2.0 is a language book that adheres to the core

C# Language 2.0 Specification To help you understand thevarious C# constructs, it provides numerous examples

demonstrating each feature Accompanying each concept areguidelines and best practices, ensuring that code compiles,avoids likely pitfalls, and achieves maximum maintainability

To improve readability, code is specially formatted and chaptersare outlined using mind maps

Code Samples

The code snippets in most of this text can run on any

implementation of the Common Language Infrastructure (CLI),including the Mono, Rotor, and Microsoft NET platforms

Platform- or vendor-specific libraries are seldom used, exceptwhen communicating important concepts relevant only to thoseplatforms (appropriately handling the single-threaded user

interface of Windows, for example) Any code that specificallyrequires C# 2.0 compliance is called out in Appendix C: C# 2.0Topics

Trang 22

static void Main()

Highlighted code calls out specific code snippets that mayhave changed from an earlier listing, or demonstrates theconcept described in the text

System.Console.Write /* No new line */ (

Highlighting can appear on an entire line or on just a fewcharacters within a line

System.Console.WriteLine(

"Your full name is {0} {1}." ,

Incomplete listings contain an ellipsis to denote irrelevantcode that has been omitted

//

Console output is the output from a particular listing thatappears following the listing

Trang 23

incorporate them into your programs The core omission is errorchecking, such as exception handling Also, code samples donot explicitly include using System statements You need to

concepts easily, with less chance of encountering very specificknowledge that you might not be looking for

Trang 24

Depending on your level of experience, special code blocks andnotes will help you navigate through the text

Language Contrast sidebars identify key differences

between C# and its predecessors to aid those familiar withother languages

present the object-advanced topics found in the remainder of this book

constructs, handling common patterns needed by virtually allmodern programs This leads to dynamic programming withreflection and attributes, which is used extensively for threadingand interoperability, the chapters that follow

Trang 25

Infrastructure, which describes C# within the context of thedevelopment platform in which it operates This chapter

appears at the end because it is not C# specific and it departsfrom the syntax and programming style in the rest of the book.However, this chapter is suitable for reading at any time,

perhaps most appropriately immediately following Chapter 1.Here is a description of each chapter

program, this chapter proceeds to dissect it This shouldfamiliarize readers with the look and feel of a C# programand provide details on how to compile and debug their ownprograms It also touches on the context of a C# program'sexecution and its intermediate language

Chapter 2Data Types: Functioning programs manipulate

data, and this chapter introduces the primitive data types ofC# This includes coverage of two type categories, valuetypes and reference types, along with conversion betweentypes and support for arrays

Chapter 3Operators and Control Flow: To take advantage of

the iterative capabilities in a computer, you need to knowhow to include loops and conditional logic within your

program This chapter also covers the C# operators, dataconversion, and preprocessor directives

Chapter 4Methods and Parameters: This chapter

investigates the details of methods and their parameters Itincludes passing by value, passing by reference, and

returning data via a parameter In C#, default parametersare not supported, and this chapter explains why and how

to provide the same functionality

Trang 26

this chapter combines these constructs together to formfully functional types Classes form the core of object-

Chapter 7Interfaces: This chapter demonstrates how

interfaces are used to define the "versionable" interactioncontract between classes C# includes both explicit and

implicit interface member implementation, enabling an

additional encapsulation level not supported by most otherlanguages

Chapter 8Value Types: Although not as prevalent as

defining reference types, it is sometimes necessary to

define value types that behave in a fashion similar to theprimitive types built into C# This chapter describes how todefine structures, while exposing the idiosyncrasies theymay introduce

Chapter 10Exception Handling: This chapter expands on the

exception-handling introduction from Chapter 4 and

describes how exceptions follow a hierarchy that enables

Trang 27

Chapter 13Delegates and Events: Delegates begin clearly

distinguishing C# from its predecessors by defining patternsfor handling events within code This virtually eliminates theneed for writing routines that poll Encapsulated delegates,known as events, are a core construct of the Common

Language Runtime Anonymous methods, another C# 2.0feature, are also presented here

Chapter 14Reflection and Attributes: Object-oriented

programming formed the basis for a paradigm shift in

program structure in the late 1980s In a similar way,

attributes facilitate declarative programming and embeddedmetadata, ushering in a new paradigm This chapter looks

Trang 28

additional precautions to protect data in these advancedenvironments Programming multithreaded applications iscomplex This chapter discusses how to work with threadsand provides best practices to avoid the problems that

of unmanaged codethrough P/Invoke In addition, C#

provides for the use of pointers and direct memory

manipulation Although code with pointers requires specialprivileges to run, it provides the power to interoperate fullywith traditional C-based application programming

interfaces

Chapter 18The Common Language Infrastructure:

Fundamentally, C# is the syntax that was designed as themost effective programming language on top of the

underlying Common Language Infrastructure This chapterdelves into how C# programs relate to the underlying

runtime and its specifications

Appendix ADownloading and Installing the C# Compiler and the CLI Platform: This appendix provides instructions for

setting up a C# compiler and the platform on which to runthe code, Microsoft NET or Mono

Appendix BComplete Source Code Listings: In several

Trang 29

3, 11, 12, 14, and 17

Appendix CC# 2.0 Topics: This appendix provides a quick

reference to any C# 2.0 content It is specifically designed

to help C# 1.0 programmers quickly get up to speed on the2.0 features

I hope you find this book to be a great resource in establishingyour C# expertise and that you continue to reference it for themore obscure areas of C# and its inner workings

Trang 30

Figure 12.3 SortedList<> and SortedDictionary<> Class Diagrams 431Figure 12.4 Stack<T> and Stack Class Diagrams 432

Figure 12.5 Queue<T> and Queue Class Diagrams 433

Figure 12.6 LinkedList<T> and LinkedListNode<T> Class Diagram 434

Trang 31

Figure 14.1 MemberInfo Derived Classes 518

Trang 33

NO BOOK CAN BE published by the author alone, and I am

extremely grateful for the multitude of people who helped mewith this one

The order in which I thank people is not significant, except forthose that come first By far, my family has made the biggestsacrifice to allow me to complete this Benjamin, Hanna, and(most recently) Abigail often had a Daddy distracted by thisbook, but Elisabeth suffered even more so She was often left totake care of things, holding the family's world together on herown Thanks honey!

Many technical editors reviewed each chapter in minute detail

to ensure technical accuracy I was often amazed by the subtleerrors that these folks still managed to catch:

Trang 34

In particular, Michael was a huge help in editing the technicalcontent and serving as a sounding board as I was putting thematerial together, not to mention his invaluable friendship I amalso especially grateful to the C# MVPs (Nicholas and John),who know the language in certain areas second only to those onthe C# team

Thanks also to all those at Addison-Wesley, for their patience inworking with me in spite of my frequent focus everywhere

an incredible jump-start on the material Thanks Prashant!

Trang 35

Mark Michaelis is an enterprise software architect at Itron

Corporation and a trainer for Pluralsight Mark holds a B.A inphilosophy from the University of Illinois and an M.S in

computer science from the Illinois Institute of Technology He is

a Microsoft MVP for the Visual Studio Team System, and heserves on several Microsoft software design review teams,

including C# and VSTS Mark speaks at developer conferences,both nationally and internationally, and has written several

Trang 36

C# is a relatively new language that builds on features found inits predecessor C-style languages (C, C++, and Java), making itimmediately familiar to many experienced programmers Part of

a larger, more complex execution platform called the CommonLanguage Infrastructure (CLI), C# is a programming languagefor building software components and applications

a summary of managed execution context, which explains how

a C# program executes at runtime This chapter ends with adiscussion of variable declaration, writing and retrieving datafrom the console, and the basics of commenting code in C#

Trang 37

The best way to learn a new programming language is to writecode The first example is the classic HelloWorld program In thisprogram, you will display some text to the screen

semicolons and curly braces), features (such as case

Trang 38

Beginners and programmers from other languages will quicklyfind these constructs intuitive

[2] When creating C#, the language creators sat down with the specifications for C/C++, literally crossing out

the features that they didn't like and creating a list of the ones they did like The group also included designers with strong backgrounds in other languages.

Compiling and Running the Application

The C# compiler allows any file extension for files containingC# source code, but .cs is typically used After saving the

source code to a file, developers must compile it (Appendix A

provides instructions for installing the compiler.) Because themechanics of the command are not part of the C# standard, thecompilation command varies depending on the C# compiler

implementation

If you place Listing 1.1 into a file called HelloWorld.cs, the

compilation command in Output 1.1 will work with the Microsoft.NET compiler (assuming appropriate paths to the compiler areset up).[3]

Trang 39

assembly regardless of whether it is a program or a library

Trang 40

machine code that the processor can understand This

Ngày đăng: 25/03/2019, 16:43