Tải bản đầy đủ (.pdf) (808 trang)

2002 oreilly learning c sharp1

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 (3.39 MB, 808 trang )




Tableof

Contents
• Index
• Reviews
Reader

Reviews
• Errata

LearningC#
ByJesseLiberty

Publisher :O'Reilly
PubDate :September2002
ISBN :0-596-00376-5
Pages :368
Slots :1



WithLearningC#,best-sellingauthorJesseLibertywill
helpyoubuildasolidfoundationin.NETandshowhowto
applyyourskillsbyusingdozensoftestedexamples.You
willlearnhowtodevelopvariouskindsofapplications-includingthosethatworkwithdatabases--andweb
services.Whetheryouhavealittleobject-oriented
programmingexperienceoryouarenewtoprogramming
altogether,LearningC#willsetyoufirmlyonyourway.






LearningC#
ByJesseLiberty


Tableof Publisher :O'Reilly

Contents PubDate :September2002
ISBN :0-596-00376-5
• Index
Pages :368
• Reviews
Slots :1
Reader

Reviews
• Errata



Copyright



Preface




AboutThisBook



WhoThisBookIsFor



HowtheBookIsOrganized



ConventionsUsedinThisBook



Support



We'dLiketoHearfromYou



Acknowledgments





Chapter1.C#and.NETProgramming



Section1.1.C#and.NET



Section1.2.The.NETPlatform



Section1.3.The.NETFramework



Section1.4.TheC#Language



Section1.5.TheStructureofC#Applications



Section1.6.TheDevelopmentEnvironment




Chapter2.GettingStartedwithC#




Section2.1.What'sinaProgram?



Section2.2.YourFirstProgram:HelloWorld



Section2.3.ExaminingYourFirstProgram




Chapter3.Object-OrientedProgramming



Section3.1.CreatingModels



Section3.2.ClassesandObjects







Section3.3.DefiningaClass



Section3.4.ClassRelationships



Section3.5.TheThreePillarsofObject-OrientedProgramming



Section3.6.Encapsulation



Section3.7.Specialization



Section3.8.Polymorphism



Section3.9.Object-OrientedAnalysisandDesign





Chapter4.VisualStudio.NET



Section4.1.StartPage



Section4.2.InsidetheIntegratedDevelopmentEnvironment(IDE)



Section4.3.IntelliSense



Section4.4.BuildingandRunning



Section4.5.ForMoreInformation




Chapter5.C#LanguageFundamentals



Section5.1.Types




Section5.2.Variables



Section5.3.DefiniteAssignment



Section5.4.Constants



Section5.5.Strings



Section5.6.Statements



Section5.7.Expressions



Section5.8.Whitespace





Chapter6.Branching



Section6.1.UnconditionalBranchingStatements



Section6.2.ConditionalBranchingStatements



Section6.3.Iteration(Looping)Statements




Chapter7.Operators



Section7.1.TheAssignmentOperator(=)



Section7.2.MathematicalOperators




Section7.3.IncrementandDecrementOperators



Section7.4.RelationalOperators




Chapter8.ClassesandObjects



Section8.1.DefiningClasses



Section8.2.MethodArguments



Section8.3.Constructors



Section8.4.Initializers




Section8.5.CopyConstructors



Section8.6.ThethisKeyword



Section8.7.StaticandInstanceMembers



Section8.8.DestroyingObjects





Chapter9.InsideMethods



Section9.1.OverloadingMethods



Section9.2.EncapsulatingDatawithProperties




Section9.3.ReturningMultipleValues




Chapter10.BasicDebugging



Section10.1.SettingaBreakpoint



Section10.2.TheCallStack




Chapter11.InheritanceandPolymorphism



Section11.1.SpecializationandGeneralization



Section11.2.Inheritance




Section11.3.Polymorphism



Section11.4.AbstractClasses



Section11.5.SealedClasses



Section11.6.TheRootofAllClasses:Object



Section11.7.BoxingandUnboxingTypes




Chapter12.OperatorOverloading



Section12.1.UsingtheoperatorKeyword



Section12.2.CreatingUsefulOperators




Section12.3.LogicalPairs



Section12.4.ConversionOperators





Chapter13.Structs
Section13.1.DefiningaStruct




Chapter14.Interfaces



Section14.1.ImplementinganInterface



Section14.2.ImplementingMoreThanOneInterface




Section14.3.CastingtoanInterface



Section14.4.ExtendingInterfaces



Section14.5.CombiningInterfaces



Section14.6.OverridingInterfaceImplementations



Section14.7.ExplicitInterfaceImplementation




Chapter15.Arrays



Section15.1.Arrays




Section15.2.MultidimensionalArrays



Section15.3.System.Array



Section15.4.Indexers





Chapter16.CollectionInterfacesandTypes
Section16.1.TheCollectionInterfaces




Section16.2.ArrayLists



Section16.3.Queues



Section16.4.Stacks




Section16.5.CopyingfromaCollectionTypetoanArray




Chapter17.Strings



Section17.1.CreatingStrings



Section17.2.ManipulatingStrings



Section17.3.RegularExpressions



Section17.4.TheRegexClass




Chapter18.ThrowingandCatchingExceptions




Section18.1.ThrowingExceptions



Section18.2.SearchingforanExceptionHandler



Section18.3.ThethrowStatement



Section18.4.ThetryandcatchStatements



Section18.5.HowtheCallStackWorks



Section18.6.CreatingDedicatedcatchStatements



Section18.7.ThefinallyStatement




Section18.8.ExceptionClassMethodsandProperties



Section18.9.CustomExceptions




Chapter19.DelegatesandEvents



Section19.1.Delegates



Section19.2.Multicasting



Section19.3.Events




Afterword




WheretoGofromHere



AdvancedTopicsinC#



Web(ASP.NET)Programming



WindowsFormsProgramming



OtherResources




C#Keywords



A



B




C



D



E



F



G



I



L




N




O



P



R



S



T



U




V



W




Colophon



Index


Copyright©2002O'Reilly&Associates,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'Reilly&Associates,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reilly&Associatesbooksmaybepurchasedforeducational,
business,orsalespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformationcontactour
corporate/institutionalsalesdepartment:800-998-9938or

NutshellHandbook,theNutshellHandbooklogo,andtheO'Reillylogo
areregisteredtrademarksofO'Reilly&Associates,Inc.Manyofthe
designationsusedbymanufacturersandsellerstodistinguishtheir
productsareclaimedastrademarks.Wherethosedesignationsappearin
thisbook,andO'Reilly&Associates,Inc.wasawareofatrademark

claim,thedesignationshavebeenprintedincapsorinitialcaps.The
associationbetweentheimageofagoldfishandthetopicofLearningC#
isatrademarkofO'Reilly&Associates,Inc.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,
thepublisherandtheauthorassumenoresponsibilityforerrorsor
omissions,orfordamagesresultingfromtheuseoftheinformation
containedherein.


Preface
InJuly2000,Microsoftannouncedthereleaseofitsnew.NETplatform,
whichrepresentedamajorchangeinthewaypeoplethinkabout
programming..NETfacilitatesobject-orientedInternetdevelopment.C#
isaprogramminglanguagethatwasdevelopedspecificallyforthe
purposeofwritingapplicationsforthe.NETplatform.C#buildson
lessonslearnedfromotherlanguages,likeC(highperformance),Java
(highsecurity),andVisualBasic(rapiddevelopment).Andthisnew
languageisideallysuitedfordevelopingdistributedwebapplications.


AboutThisBook
LearningC#isaprimerontheC#language,inthecontextofthe.NET
developmentenvironment,andalsoonobject-orientedprogramming.
ThisbookfocusesonthefundamentalsoftheC#programming
language,bothsyntacticalandsemantic.Aftermasteringtheseconcepts,
youshouldbereadytomoveontoamoreadvancedprogrammingguide
thatwillhelpyoucreatelarge-scalewebandWindowsapplications.
Afterword,providesanumberofsuggestionsforyourcontinuedstudyof
C#and.NETdevelopment.



WhoThisBookIsFor
LearningC#waswrittenforprogrammerswithlittleornoobject-oriented
programmingexperience,aswellasfornoviceprogrammers.Those
comingfromanotherlanguagemayhaveaslightadvantage,butI've
triedtoprovideanon-rampforbeginnersaswell,bydefiningallterms,
demonstratingtherelationshipsamongthevariousconstructs,and
reviewingkeyconceptsalongtheway.


HowtheBookIsOrganized
Chapter1,introducesyoutotheC#languageandthe.NETplatform.
Chapter2,presentsasimpleapplicationthatprintsthewords"Hello
World"toaconsolewindow,andgivesaline-by-lineanalysisofthecode.
Chapter3,explainstheprinciplesbehindandgoalsofthisprogramming
methodology,includingthethreepillarsofobject-orientedprogramming:
encapsulation,specialization,andpolymorphism.
Chapter4,introducestheIntegratedDevelopmentEnvironment(IDE)
designedspecificallyfor.NET;usingtheIDEcangreatlysimplifyhowyou
writeapplications.
Chapter5,introducesthebasicsyntaxandstructureoftheC#language,
includingtheintrinsictypes,variables,statements,andexpressions.
Chapter6,describessomeofthewaysyoucanchangetheorderin
whichmethodsarecalledwithinaprogram.Statementssuchasif,
switch,goto,andbreakwillbeconsidered,alongwiththeconceptof
loops,whicharecreatedusingsuchkeywordsasfor,while,and
do...while.
Chapter7,describessomeofthesymbolsthatcauseC#totakean
action,suchasassigningavaluetoavariableandarithmetically
operatingonvalues(adding,subtracting,andsoforth).

Chapter8,introducesthekeyconceptsofprogrammer-definedtypes
(classes)andinstancesofthosetypes(objects).Classesandobjectsare
thebuildingblocksofobject-orientedprogramming.
Chapter9,delvesintothespecificprogramminginstructionsyou'llwrite
todefinethebehaviorofobjects.
Chapter10,introducesthedebuggerintegratedintotheVisualStudio


.NETIntegratedDevelopmentEnvironment.
Chapter11,explorestwoofthekeyconceptsbehindobject-oriented
programminganddemonstrateshowyoumightimplementtheminyour
code.
Chapter12,explainshowtoaddstandardoperatorstothetypesyou
define.
Chapter13,introducesthestructureorstruct,aprogrammer-definedtype
similartoaclass,butwithspecificandmorelimitedfunctionality.
Chapter14,explainshowyoucandefineasetofbehaviors(aninterface)
thatanynumberofclassesmightimplement.
Chapter15,introducesthearray,anindexedcollectionofobjectsthatare
allthesametype.Arraysareoneofthecollectiontypesrecognizedby
C#.
Chapter16,describessomeoftheotherC#collections,includingstacks
andqueues.
Chapter17,discussesthemanipulationofstringsofcharacters,theC#
stringclass,andregularexpressionsyntax.
Chapter18,explainshowtohandleerrorsandabnormalconditionsthat
mayariseinrelationtoyourprograms.
Chapter19,discusseshowtowritecodetorespondtoprogramming
occurrenceslikemouseclicks,keystrokes,andotherevents;event
handlingisoftenaccomplishedbytheuseofdelegates,whichare

objectsthatencapsulateanymethodthatmatchesthedelegate's
specification.
Afterword,describeswhereyoumightgotolearnmoreaboutC#and
.NETprogramming,includingotherbooks,websites,newsgroups,and
soforth.
ThebookconcludeswithanappendixofC#Keywords.


ConventionsUsedinThisBook
Thefollowingfontconventionsareusedinthisbook:
Italic
Usedforpathnames,filenames,programnames,Internetaddresses,
suchasdomainnamesandURLs,andnewtermswheretheyare
defined.
ConstantWidth
Usedforcommandlinesandoptionsthatshouldbetypedverbatim,
C#keywords,andcodeexamples.
ConstantWidthItalic
Usedforreplaceableitems,suchasvariablesoroptionalelements,
withinsyntaxlinesorcode.
ConstantWidthBold
Usedforemphasiswithinprogramcode.
Payspecialattentiontonotessetapartfromthetextwiththefollowing
icons:
Thisisatip.Itcontainsusefulsupplementaryinformationabout
thetopicathand.

Thisisawarning.Ithelpsyousolveandavoidannoying
problems.



Support
Aspartofmyresponsibilitiesasauthor,Iprovideongoingsupportformy
booksthroughmywebsite:

Onthiswebsite,you'llalsofindthesourcecodeforalltheexamplesin
LearningC#,aswellasaccesstoabook-supportdiscussiongroupwitha
sectionsetasideforquestionsaboutC#.Beforeyoupostaquestion,
however,pleasechecktheFAQ(FrequentlyAskedQuestions)listand
theerratafileonmywebsite.Ifyoucheckthesefilesandstillhavea
question,thenpleasegoaheadandposttothediscussioncenter.
Themosteffectivewaytogethelpistoaskaveryprecisequestionor
eventocreateaverysmallprogramthatillustratesyourareaofconcern
orconfusion.Youmayalsowanttocheckthevariousnewsgroupsand
discussioncentersontheInternet.Microsoftoffersawidearrayof
newsgroups,andDevelopmentor()has
wonderful.NETemaildiscussionlist,asdoesCharlesCarrollat
.


We'dLiketoHearfromYou
Wehavetestedandverifiedtheinformationinthisbooktothebestofour
ability,butyoumayfindthatfeatureshavechanged(oreventhatwe
havemademistakes!).Pleaseletusknowaboutanyerrorsyoufind,as
wellasyoursuggestionsforfutureeditions,bywritingto:
O'Reilly&Associates,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheU.S.orCanada)
(707)829-0515(international/local)

(707)829-0104(fax)
Wehaveawebpageforthisbookwherewelistexamplesandanyplans
forfutureeditions.Youcanaccessthisinformationat:
/>Youcanalsosendmessageselectronically.Tobeputonthemailinglist
orrequestacatalog,sendemailto:

Tocommentonthebook,sendemailto:

Formoreinformationaboutthisbookandothers,aswellasadditional
technicalarticlesanddiscussionontheC#andthe.NETFramework,see
theO'Reilly&Associateswebsite:

andtheO'Reilly.NETDevCenter:
/>

ONDotnet.comprovidesindependentcoverageoffundamental,
interoperable,andemergingMicrosoft.NETprogrammingandWeb
servicestechnologies.


Acknowledgments
ToensurethatLearningC#isaccurate,complete,andtargetedatthe
needsandinterestsofprogrammers,Ienlistedthehelpofsomeofthe
brightestpeopleIknow,includingDanHurwitz,SethWeiss,andSue
Lynch.
JohnOsbornsignedmetoO'Reilly,forwhichIwillforeverbeinhisdebt.
ClaireCloutierandTatianaDiazhelpedmakethisbookbetterthanwhat
I'dwritten.RobRomanocreatedanumberoftheillustrationsand
improvedtheothers.TimO'Reillyprovidedsupportandresources,and
I'mgrateful.AspecialthankyoutoValQuercia,whoaddedgreatvalueto

thisbook,asshehastomanyothers.Ifthisbookisclearand
understandable,itisduetohervigilance.


Chapter1.C#and.NETProgramming
LearningC#introducesC#specifically,andthe.NETdevelopment
platformmoregenerally,toprogrammerswithlittleornoobject-oriented
programmingexperience.Alongtheway,youwilllearnagreatdealabout
writinghigh-quality,industrial-strengthprogramsfor.NET.
ThisbriefintroductionwillshowyouhowC#fitsintothe.NETpicture,
whatyoucandowiththelanguage,andwhatbenefitsthislanguagehas
overitspredecessors.
Youwillalsolearnsomeoftheconceptsintegraltoobject-oriented
programming,whichhasrevolutionizedhowwebandWindows
applicationsaredeveloped.Object-orientedprogrammingiscloselytied
tothesemanticsoftheC#language,thatis,themeaningbehindthe
codeyouwrite.Obviously,youneedtohaveabasicunderstandingofthe
syntaxoftheC#language,butyoualsoneedtounderstandwhatyouare
actuallytryingtoaccomplish.


1.1C#and.NET
Inthepast,youmighthavelearnedalanguagelikeCorJavawithout
muchconcernabouttheplatformonwhichyouwouldbeprogramming.
Thesecross-platformlanguageswereascomfortableonaUnixboxas
theywereonaPCrunningWindows.
C#,however,wascreatedspecificallyfor.NET.While.NETmaybecome
cross-platformsomedaysoonaUnixportisreportedlyintheoffingfor
nowtheoverwhelmingmajorityof.NETprogramswillbewrittentorunon
amachinerunning.NET.Atthetimeofthiswriting,thatmeansa

Windowsmachine.


1.2The.NETPlatform
WhenMicrosoftannouncedC#inJuly2000,itsunveilingwaspartofa
muchlargerevent:theannouncementofthe.NETplatform.The.NET
platformisadevelopmentframeworkthatprovidesanewwaytocreate
Windowsapplications.However,.NETgoesbeyondtraditionalWindows
programmingtofacilitatecreatingwebapplicationsquicklyandeasily.
Microsoftsaysitisdevoting80%ofitsresearchanddevelopmentbudget
to.NETanditsassociatedtechnologies.Theresultsofthiscommitment
areimpressive.Foronething,thescopeof.NETishuge.Theplatform
consistsofthreeseparateproductgroups:
Asetoflanguages,includingC#andVisualBasic.NET;asetof
developmenttools,includingVisualStudio.NET;andpowerfultools
forbuildingapplications,includingtheCommonLanguageRuntime
(CLR),aplatformforcompiling,debugging,andexecuting.NET
applications.
Asetof.NETEnterpriseServers,formerlyknownasSQLServer
2000,Exchange2000,BizTalk2000,andsoon,thatprovide
specializedfunctionalityforrelationaldatastorage,email,B2B
commerce,etc.
New.NET-enablednon-PCdevices,fromcellphonestogame
boxes.
TheC#languagecanbeusedtodevelopthreetypesofapplicationsyou
canrunonyourWindowscomputer:
Consoleapplications,whichdisplaynographics
Windowsapplications,whichusethestandardWindowsinterface
Webapplications,whichcanbeaccessedwithabrowser



ThisbookwillfocusprimarilyonthebasicsoftheC#language,mostly
usingsimpleconsoleapplicationstoillustratelanguagefundamentals.


1.3The.NETFramework
Centraltothe.NETplatformisadevelopmentenvironmentknownasthe
.NETFramework.TheFrameworkspecifieshow.NETprogramming
constructssuchasintrinsictypes,classes,andinterfacesare
implemented.Youwilllearnabouttheseconstructsinthechapters
ahead.
The.NETFrameworksitsontopofanyflavoroftheWindowsoperating
system.ThemostimportantcomponentsoftheFrameworkarethe
CommonLanguageRuntime(CLR),describedintheprecedingsection,
andtheFrameworkClassLibrary(FCL),whichprovidesanenormous
numberofpredefinedtypesorclassesforyoutouseinyourprograms.
YouwilllearnhowtodefineyourownclassesinChapter8.Complete
coverageofalltheFCLclassesisbeyondthescopeofthisbook.For
moreinformation,seeC#inaNutshell(O'Reilly&Associates).


1.4TheC#Language
TheC#languageisdisarminglysimple,butC#ishighlyexpressivewhen
itcomestoimplementingmodernprogrammingconcepts.C#includesall
thesupportforstructured,component-based,object-oriented
programmingthatoneexpectsofamodernlanguagebuiltonthe
shouldersofC++andJava.
AsmallteamledbytwodistinguishedMicrosoftengineers,Anders
HejlsbergandScottWiltamuth,developedtheC#language.Hejlsbergis
alsoknownforcreatingTurboPascal,apopularlanguageforPC

programming,andforleadingtheteamthatdesignedBorlandDelphi,
oneofthefirstsuccessfulIntegratedDevelopmentEnvironmentsfor
client/serverprogramming.
ThegoalofC#istoprovideasimple,safe,object-oriented,Internetcentric,high-performancelanguagefor.NETdevelopment.C#issimple
becausetherearerelativelyfewkeywords.Thismakesiteasytolearn
andeasytoadapttoyourspecificneeds.
Keywordsarespecialwordsreservedbythelanguagethat
haveaspecificmeaningwithinallC#programs.Keywords
includeif,while,andfor.You'lllearnaboutthesekeywords
inthecomingchapters.

C#isconsideredsafebecauseitprovidessupportinthelanguagetofind
bugsearlyinthedevelopmentprocess.Thismakesforcodethatis
easiertomaintainandprogramsthataremorereliable.
C#wasdesigned,fromtheverystart,tosupportobject-oriented
programming.Thisbookwillexplainnotonlyhowtowriteobject-oriented
programs,butalsowhyobject-orientedprogramminghasbecomeso
popular.Theshortansweristhis:programsarebecomingincreasingly
complex,andobject-orientedprogrammingtechniqueshelpyoumanage


thatcomplexity.
C#wasdesignedfor.NET,and.NETwasdesignedfordevelopingweb
andweb-awareprograms.TheInternetisaprimaryresourceinmost
.NETapplications.
Finally,C#wasdesignedforprofessionalhigh-performance
programming.


1.5TheStructureofC#Applications

Atthemostfundamentallevel,aC#applicationconsistsofsourcecode.
Sourcecodeishuman-readabletextwritteninatexteditor.Atexteditor
islikeawordprocessor,butitputsnospecialcharactersintothefileto
supportformatting,onlythetext.AclassictexteditorisNotepad.
Example1-1showsanexampleofaverysimplesourcecodefile.
Example1-1.Asourcecodefile
namespaceNotePad
{
classHelloWorld
{
//everyconsoleappstartswithMain
staticvoidMain()
{
System.Console.WriteLine("Helloworld!");
}
}
}
ThisprogramisexplainedindetailinChapter2.Fornow,observethat
theprogramitselfisreadable;itisinnormaltext.Thewordsmaybe


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×