Tải bản đầy đủ (.pdf) (1,002 trang)

OReilly learning c sharp 2005 get started with c sharp 2 0 and dot NET programming 2nd edition feb 2006 ISBN 0596102097

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.8 MB, 1,002 trang )

LearningC#2005
ByJesseLiberty,BrianMacDonald
...............................................
Publisher:O'Reilly
PubDate:February2006
PrintISBN-10:0-596-10209-7
PrintISBN-13:978-0-59-610209-8
Pages:552

TableofContents|Index

Ifyou'reanoviceprogrammerandyouwanttolearnC#,therearen'tmanybooksthat
willguideyou.MostC#booksarewrittenforexperiencedC++andJavaprogrammers.
That'swhyJesseLiberty,authorofthebest-sellingbooksProgrammingC#and
ProgrammingASP.NET,haswrittenanentry-levelguidetoC#.
Writteninawarmandfriendlymanner,LearningC#assumesnopriorprogramming
experience,andprovidesathoroughintroductiontoMicrosoft'spremier.NETlanguage.
Thebookhelpsyoubuildasolidfoundationin.NET,andshowsyouhowtoapplyyour
skillsthroughtheuseofdozensoftestedexamples.You'lllearnaboutthesyntaxand
structureoftheC#language,includingoperators,classesandinterfaces,structs,arrays,
andstrings.

Betteryet,thisupdatededitionofLearningC#hasbeencompletelyrevisedtoincludethe
verylatestcontentandteachingtechniques.Here'swhat'snew:
AdetailedexplanationofC#2.0
AnintroductiontoVisualStudio2005,atoolsetforbuildingWindowsandweb
applications
Morethan200questionsandprogrammingexercisestohelpyoubetterjudgeyour
understandingofthematerial
Agreateremphasisoneventhandling
Informationongenericsandgenericcollections




Bythetimeyou'vefinishedLearningC#,you'llbereadytomoveontoamoreadvanced
programmingguidethatwillhelpyoucreatelarge-scalewebandWindowsapplications.

Whetheryouhavealittleobject-orientedprogrammingexperienceoryouarenewto
programmingaltogether,LearningC#willsetyoufirmlyonyourwaytomasteringthe
essentialsoftheC#language.


LearningC#2005
ByJesseLiberty,BrianMacDonald
...............................................
Publisher:O'Reilly
PubDate:February2006
PrintISBN-10:0-596-10209-7
PrintISBN-13:978-0-59-610209-8
Pages:552

TableofContents|Index

















































LearningC#2005,SecondEdition
Dedication
Preface
AboutThisBook
WhoThisBookIsFor
HowtheBookIsOrganized
ConventionsUsedinThisBook
UsingCodeExamples
Support
We'dLiketoHearfromYou
Safari®Enabled
Acknowledgments
Chapter1.C#and.NETProgramming
Section1.1.C#2005and.NET2.0
Section1.2.The.NETPlatform
Section1.3.The.NET2.0Framework
Section1.4.TheC#Language
Section1.5.TheStructureofC#Applications
Section1.6.TheDevelopmentEnvironment
Section1.7.What'sinaProgram?
Section1.8.YourFirstProgram:HelloWorld
Section1.9.TheCompiler
Section1.10.ExaminingYourFirstProgram

Section1.11.Summary
















































































Section1.12.Quiz
Section1.13.Exercise
Chapter2.VisualStudio2005
Section2.1.BeforeYouReadFurther
Section2.2.StartPage
Section2.3.ProjectsandSolutions
Section2.4.InsidetheIntegratedDevelopmentEnvironment
Section2.5.BuildingandRunning
Section2.6.MenusandToolbars
Section2.7.Summary
Section2.8.Quiz

Section2.9.Exercise
Chapter3.C#LanguageFundamentals
Section3.1.Statements
Section3.2.Types
Section3.3.Variables
Section3.4.DefiniteAssignment
Section3.5.Constants
Section3.6.Strings
Section3.7.Expressions
Section3.8.Whitespace
Section3.9.Summary
Section3.10.Quiz
Section3.11.Exercises
Chapter4.Operators
Section4.1.TheAssignmentOperator(=)
Section4.2.MathematicalOperators
Section4.3.IncrementandDecrementOperators
Section4.4.RelationalOperators
Section4.5.Summary
Section4.6.Quiz
Section4.7.Exercises
Chapter5.Branching
Section5.1.UnconditionalBranchingStatements
Section5.2.ConditionalBranchingStatements
Section5.3.Iteration(Looping)Statements
Section5.4.Summary
Section5.5.Quiz
Section5.6.Exercises
















































































Chapter6.Object-OrientedProgramming
Section6.1.CreatingModels
Section6.2.ClassesandObjects
Section6.3.DefiningaClass
Section6.4.ClassRelationships
Section6.5.TheThreePillarsofObject-OrientedProgramming
Section6.6.Object-OrientedAnalysisandDesign
Section6.7.Summary
Section6.8.Quiz
Section6.9.Exercises
Chapter7.ClassesandObjects
Section7.1.DefiningClasses
Section7.2.MethodArguments
Section7.3.Constructors
Section7.4.Initializers

Section7.5.ThethisKeyword
Section7.6.StaticandInstanceMembers
Section7.7.DestroyingObjects
Section7.8.MemoryAllocation:TheStackVersustheHeap
Section7.9.Summary
Section7.10.Quiz
Section7.11.Exercises
Chapter8.InsideMethods
Section8.1.OverloadingMethods
Section8.2.EncapsulatingDatawithProperties
Section8.3.ReturningMultipleValues
Section8.4.Summary
Section8.5.Quiz
Section8.6.Exercises
Chapter9.BasicDebugging
Section9.1.SettingaBreakpoint
Section9.2.ExaminingValues:TheAutosandLocalsWindows
Section9.3.SetYourWatch
Section9.4.TheCallStack
Section9.5.Summary
Section9.6.Quiz
Section9.7.Exercises
Chapter10.Arrays
Section10.1.UsingArrays


















































































Section10.2.TheforeachStatement
Section10.3.InitializingArrayElements
Section10.4.TheparamsKeyword
Section10.5.MultidimensionalArrays
Section10.6.ArrayMethods
Section10.7.SortingArrays
Section10.8.Summary
Section10.9.Quiz
Section10.10.Exercises
Chapter11.InheritanceandPolymorphism
Section11.1.SpecializationandGeneralization
Section11.2.Inheritance
Section11.3.Polymorphism
Section11.4.AbstractClasses
Section11.5.SealedClasses
Section11.6.TheRootofAllClasses:Object
Section11.7.BoxingandUnboxingTypes

Section11.8.Summary
Section11.9.Quiz
Section11.10.Exercises
Chapter12.OperatorOverloading
Section12.1.UsingtheoperatorKeyword
Section12.2.CreatingUsefulOperators
Section12.3.TheEqualsOperator
Section12.4.ConversionOperators
Section12.5.Summary
Section12.6.Quiz
Section12.7.Exercises
Chapter13.Interfaces
Section13.1.ImplementinganInterface
Section13.2.ImplementingMorethanOneInterface
Section13.3.CastingtoanInterface
Section13.4.TheisandasOperators
Section13.5.ExtendingInterfaces
Section13.6.CombiningInterfaces
Section13.7.OverridingInterfaceImplementations
Section13.8.ExplicitInterfaceImplementation
Section13.9.Summary
Section13.10.Quiz

















































































Section13.11.Exercises
Chapter14.GenericsandCollections
Section14.1.Generics
Section14.2.CollectionInterfaces
Section14.3.CreatingYourOwnCollections
Section14.4.FrameworkGenericCollections
Section14.5.Summary
Section14.6.Quiz
Section14.7.Exercises
Chapter15.Strings
Section15.1.CreatingStrings
Section15.2.ManipulatingStrings
Section15.3.RegularExpressions
Section15.4.TheRegexClass
Section15.5.Summary
Section15.6.Quiz
Section15.7.Exercises
Chapter16.ThrowingandCatchingExceptions
Section16.1.Bugs,Errors,andExceptions
Section16.2.ThrowingExceptions

Section16.3.SearchingforanExceptionHandler
Section16.4.ThethrowStatement
Section16.5.ThetryandcatchStatements
Section16.6.HowtheCallStackWorks
Section16.7.CreatingDedicatedcatchStatements
Section16.8.ThefinallyStatement
Section16.9.ExceptionClassMethodsandProperties
Section16.10.CustomExceptions
Section16.11.Summary
Section16.12.Quiz
Section16.13.Exercises
Chapter17.DelegatesandEvents
Section17.1.Delegates
Section17.2.Multicasting
Section17.3.Events
Section17.4.UsingAnonymousMethods
Section17.5.Summary
Section17.6.Quiz
Section17.7.Exercises












































Chapter18.CreatingWindowsApplications





































Section18.1.CreatingaSimpleWindowsForm
Section18.2.CreatingaReal-WorldApplication
Section18.3.XMLDocumentationComments
Section18.4.Summary
Section18.5.Quiz
Section18.6.Exercises
Chapter19.ProgrammingASP.NETApplications
Section19.1.UnderstandingWebForms
Section19.2.WebFormEvents
Section19.3.CreatingaWebForm
Section19.4.AddingControls
Section19.5.ServerControls
Section19.6.DataBinding
Section19.7.AddingControlsandEvents
Section19.8.Summary
Section19.9.Quiz
Section19.10.Exercises
AppendixA.AnswerstoQuizzesandExercises
SectionA.1.Chapter1:C#and.NETProgramming
SectionA.2.Chapter2:VisualStudio2005
SectionA.3.Chapter3:C#LanguageFundamentals
SectionA.4.Chapter4:Operators

SectionA.5.Chapter5:Branching
SectionA.6.Chapter6:Object-OrientedProgramming
SectionA.7.Chapter7:ClassesandObjects
SectionA.8.Chapter8:InsideMethods
SectionA.9.Chapter9:BasicDebugging
SectionA.10.Chapter10:Arrays
SectionA.11.Chapter11:InheritanceandPolymorphism
SectionA.12.Chapter12:OperatorOverloading
SectionA.13.Chapter13:Interfaces
SectionA.14.Chapter14:GenericsandCollections
SectionA.15.Chapter15:Strings
SectionA.16.Chapter16:ThrowingandCatchingExceptions
SectionA.17.Chapter17:DelegatesandEvents
SectionA.18.Chapter18:CreatingWindowsApplications
SectionA.19.Chapter19:ProgrammingASP.NETApplications
AbouttheAuthor




Colophon



Index


LearningC#2005,SecondEdition
byJesseLibertyandBrianMacDonald
Copyright©2006,2002O'ReillyMedia,Inc.Allrightsreserved.

PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

JohnOsborn

ProductionEditor:

MattHutchinson

ProductionServices:

OctalPublishing,Inc.

CoverDesigner:

HannaDyer

InteriorDesigner:

DavidFutato

Illustrators:


RobertRomano,JessamynRead,andLesleyBorash

PrintingHistory:



September2002:

FirstEdition.


February2006:

SecondEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
LearningC#2005,theimageofagoldfish,andrelatedtrade
dressaretrademarksofO'ReillyMedia,Inc.
Microsoft,MSDN,the.NETlogo,VisualBasic,VisualC++,
VisualStudio,andWindowsareregisteredtrademarksof
MicrosoftCorporation.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof

theinformationcontainedherein.
ISBN:0-596-10209-7
[M]




Dedication
ThisbookisdedicatedtotheNationalEating
DisorderAssociationandtoSomethingFishy.organdtoallthosewhostruggletoovercome
thesemostdangerousandmisunderstood
afflictions.



Preface
Inthesummerof2000,MicrosoftreleasedC#1.0,which
togetherwiththe.NETFramework,representedamajorchange
inthewayWindowsapplicationsandwebapplicationswereto
bebuilt.
InNovember2005,MicrosoftreleasedC#2.0,alsoknownas
C#2005,andanupgradedplatform,classlibrary,andsetof
tools,includingVisualStudio2005.Throughoutthisbook,we'll
refertoC#2.0asC#2005.Althoughnotquiteasrevolutionary
astepasthelaunchof.NETitself,2.0representsasignificant
maturationofthe.NETplatformandoftheC#language,along
withgreatlyenhancedtoolstosignificantlyincrease
programmerproductivity.



AboutThisBook
LearningC#2005,SecondEditionisaprimerontheC#2005
languagespecifically,andobject-orientedsoftwaredevelopment
ingeneral.ThisbookfocusesonthefundamentalsoftheC#
programminglanguage,bothsyntacticalandsemantic.After
masteringtheseconcepts,youshouldbereadytomoveontoa
moreadvancedprogrammingguidethatwillhelpyoucreate
large-scalewebandWindowsapplications.


WhoThisBookIsFor
LearningC#2005waswrittenforprogrammerswithlittleorno
object-orientedprogrammingexperience,aswellasfornovice
programmers.Thosecomingfromanotherlanguagemayhave
aslightadvantage,butI'vetriedtoprovideanon-rampfor
beginnersaswell,bydefiningallterms,demonstratingthe
relationshipsamongthevariousconstructs,andreviewingkey
conceptsalongtheway.


HowtheBookIsOrganized

Chapter1,C#and.NETProgramming
IntroducesyoutotheC#languageandthe.NETplatform.

Chapter2,VisualStudio2005
ProvidesaguidedtourofVisualStudio2005thetoolyouwill
usetobuildalltheapplicationsinthebook,andperhapsall
theapplicationsyou'llbuildfromnowon.


Chapter3,C#LanguageFundamentals
IntroducesthebasicsyntaxandstructureoftheC#
language,includingtheintrinsictypes,variables,
statements,andexpressions.

Chapter4,Operators
DescribessomeofthesymbolsthatcauseC#totakean
action,suchasassigningavaluetoavariableand
arithmeticallyoperatingonvalues(adding,subtracting,and
soforth).

Chapter5,Branching
Showshowtocreateprogramsthatbranchbasedon


conditionsthatmaychangewhiletheprogramisrunning.

Chapter6,Object-OrientedProgramming
Explainstheprinciplesbehindobject-orientedprogramming,
includingencapsulation,specialization,andpolymorphism.

Chapter7,ClassesandObjects
Introducesthekeyconceptsofprogrammer-definedtypes
(classes)andinstancesofthosetypes(objects).Classes
andobjectsarethebuildingblocksofobject-oriented
programming.

Chapter8,InsideMethods
Delvesintothespecificprogramminginstructionsyou'll
writetodefinethebehaviorofobjects.


Chapter9,BasicDebugging
IntroducesthedebuggerintegratedintotheVisualStudio
2005IntegratedDevelopmentEnvironment.

Chapter10,Arrays
Introducesthearray,anindexedcollectionofobjectsthat
areallthesametype.


Chapter11,InheritanceandPolymorphism
Explorestwoofthekeyconceptsbehindobject-oriented
programming,inheritanceandpolymorphism,and
demonstrateshowyoumightimplementtheminyourcode.

Chapter12,OperatorOverloading
Explainshowtoaddstandardoperatorstothetypesyou
define.

Chapter13,Interfaces
Explainshowyoucandefineasetofbehaviors(an
interface)thatanynumberofclassesmightimplement.

Chapter14,GenericsandCollections
Explainsgenericsandshowshowgenericsareusedto
createtype-safeandefficientcollections.Chapter14then
introducesthestandard.NETFrameworkgeneric
collections:List,Stack,Queue,andDictionary.

Chapter15,Strings

Discussesthemanipulationofstringsofcharacters,theC#
stringclass,andregularexpressionsyntax.

Chapter16,ThrowingandCatchingExceptions


Explainshowtohandleerrorsandabnormalconditionsthat
mayariseinrelationtoyourprogramsthroughtheuseof
exceptions.

Chapter17,DelegatesandEvents
Discusseshowtowritecodetorespondtoprogramming
occurrenceslikemouseclicks,keystrokes,andother
events,throughtheuseofdelegatesandtheevent
keyword.

Chapter18,CreatingWindowsApplications
Showsyouhowtobringalltheseskillstobeartocreatea
Windowsapplication.

Chapter19,ProgrammingASP.NETApplications
Appliesthesameskillstobuildingawebapplication.

Appendix,AnswerstoQuizzesandExercises
Answerstoallthechapterquizzesandexercises,with
completecodeexamples.


ConventionsUsedinThisBook
Thefollowingfontconventionsareusedinthisbook:


Italic
Usedforpathnames,filenames,programnames,Internet
addresses(suchasdomainnamesandURLs),andnew
termswheretheyaredefined

ConstantWidth
Usedforcommandlinesandoptionsthatshouldbetyped
verbatim,C#keywords,andcodeexamples

ConstantWidthItalic

Usedforreplaceableitems,suchasvariablesoroptional
elements,withinsyntaxlinesorcode

ConstantWidthBold
Usedforemphasiswithinprogramcode
Payspecialattentiontonotessetapartfromthetextwiththe
followingicons:

Thisisatip.Itcontainsusefulsupplementaryinformationaboutthe
topicathand.


Thisisawarning.Ithelpsyousolveandavoidannoyingproblems.


UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand

documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"LearningC#2005,SecondEdition,byJesseLiberty
andBrianMacDonald.Copyright2006O'ReillyMedia,Inc.,0596-10209-7."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat



Support
Iprovideongoingsupportformybooksthroughmywebsite
(clickon"books"):

Onthiswebsite,you'llalsofindthesourcecodeforallthe
examplesinLearningC#2005,SecondEdition,aswellas
accesstoafreeonlinesupportdiscussionforum.You'llalsofind
anerrata,FAQ,andotherusefulresources.





We'dLiketoHearfromYou
Wehavetestedandverifiedtheinformationinthisbooktothe
bestofourability,butyoumayfindthatfeatureshavechanged
(oreventhatwehavemademistakes!).Pleaseletusknow
aboutanyerrorsyoufind,aswellasyoursuggestionsforfuture
editions,bywritingto:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheU.S.orCanada)
(707)829-0515(international/local)
(707)829-0104(fax)
Wehaveawebpageforthisbookwherewelistexamplesand
anyplansforfutureeditions.Youcanaccessthisinformation
at:
/>Youcanalsosendmessageselectronically.Tobeputonthe
mailinglistorrequestacatalog,sendemailto:

Tocommentonthebook,sendemailto:

Formoreinformationaboutthisbookandothers,aswellas
additionaltechnicalarticlesanddiscussionontheC#andthe
.NETFramework,seetheO'Reillywebsite:

andtheO'Reilly.NETDevCenter:


/>ONDotnet.comprovidesindependentcoverageoffundamental,
interoperable,andemergingMicrosoft.NETprogrammingand

webservicestechnologies.


×