Tải bản đầy đủ

Addison wesley from java to c sharp a developers guide jan 2003 ISBN 0321136225



TableofContents

FromJavatoC#:ADeveloper'sGuide
ByHengNgeeMok
Publisher :AddisonWesley
PubDate :January17,2003
ISBN :0-321-13622-5
Pages :464

Learninganewprogramminglanguagecanbe
intimidating,especiallyifyouneedtogetupand
runningwithitquickly.IfyouareacurrentJava
developerwhoneedstolearnC#,thisbookis
essential.JavaandC#sharemanycommon
characteristicsandbyfocussingonthekey
similaritiesanddifferencesbetweenthetwo
languages,FromJavatoC#:ADeveloper'sGuide
enablesyoutouseyourexistingknowledgeof
object-orientedconceptstolearnC#efficientlyand

quickly.However,featuresofC#thataretotally


absentinJavaaregiventhedetaileddescription
theywarrant.
Thispracticalguidewillhelpyoumoveeasilyfrom
JavaandJ2EEtoC#and.NETconceptsasquickly
aspossible.
FromJavatoC#:ADeveloper'sGuide:
AllowsJavadeveloperstolearnC#quicklyby
highlightingthedifferencesandsimilarities
betweenthetwolanguages
Containsextensivedetailedcoverageoffeatures
inC#thatarenotfoundinJava
Hasausefulintroductiontothe.NETplatform
andexplainshowthenewarchitectureworks
Illustratedthroughoutwithawealthofcode
exampleswhichareshortyetcomprehensive.






TableofContents

FromJavatoC#:ADeveloper'sGuide
ByHengNgeeMok
Publisher :AddisonWesley
PubDate :January17,2003
ISBN :0-321-13622-5
Pages :464

Copyright
Abouttheauthor
Preface
Introduction
Targetedaudience
Softwareprerequisites
Whatthisbookcovers


Typographicconventionsused
Codes
Erratadiscoveries
Trademarks
Structureofthebook
Acknowledgments
Part1.
Introducing.NETandC#
Chapter1.


Introducing.NET
Section1.1.
Evolution:fromCOMto.NET
Section1.2.
Whatexactlyis.NET?
Section1.3.
Multiple.NETprogramminglanguagesandVS.NET
Section1.4.
Intermediatelanguage
Section1.5.
The.NETCommonLanguageRuntime
Section1.6.
CompetinginparallelwithJavatechnologies
Section1.7.
Commonlanguageinfrastructure
Section1.8.
Other.NET-relatedtechnologies
Section1.9.
Unsafecodesandrealtimeprograms
Section1.10.
Porting.NETtootheroperatingsystems
Chapter2.
IntroducingC#
Section2.1.
PotentcomboofJavaandC++
Chapter3.
JUMPto.NETandJ#


Section3.1.
JavaLanguageConversionAssistant
Section3.2.
TheJ#language
Chapter4.
HelloC#!
Section4.1.
Howtocompileandrunthecodeexamplesinthisbook
Section4.2.
Some.NETspecifics
Section4.3.
Disassemblinganassemblyfile
Part2.
Classes,methodsandotherOOstuff
Chapter5.
Gettingstarted
Section5.1.
Basicclassstructure
Section5.2.
BasicconsoleI/O
Section5.3.
C#namespaces(Javapackages)
Chapter6.
Classissues
Section6.1.
Classmodifiers
Section6.2.
Classmembers


Section6.3.
Creatinganobjectwiththenewoperator
Section6.4.
LookingatSystem.Object
Section6.5.
Classinheritance
Section6.6.
Implementinginterfaces
Section6.7.
Sealedclasses(Javafinalclasses)
Section6.8.
Abstractclasses
Section6.9.
Nestedclasses(Javainnerclasses)
Chapter7.
Methodissues
Section7.1.
Methodmodifiers
Section7.2.
Methodbasics
Section7.3.
Instanceconstructors
Section7.4.
Staticconstructors(Javastaticinitializers)
Section7.5.
Destructors
Section7.6.


Constructorinitializersandconstructorchaining
Section7.7.
Methodoverloading
Section7.8.
PassingvariablenumbersofparametersintoC#methods
Section7.9.
Abstractmethods
Section7.10.
MethodoverridingusingthevirtualandoverrideModifiers
Section7.11.
Methodhidingwiththenewkeyword
Section7.12.
Staticmethods
Section7.13.
Sealedmethods(Javafinalmethods)
Chapter8.
Miscellaneousissues
Section8.1.
Accessmodifiers
Section8.2.
Staticmembers
Section8.3.
C#constantsandread-onlyfields(Javafinalvariables)
Section8.4.
Volatilefields
Part3.
Types,operators,andflowcontrol


Chapter9.
C#types
Section9.1.
Pointertypes
Section9.2.
Referencetypes
Section9.3.
Valuetypes
Section9.4.
UnsignedtypesinC#
Section9.5.
Thedecimaltype
Section9.6.
Thechartype
Section9.7.
Thestringtypeandstringliterals
Section9.8.
Alltypesareobjects
Section9.9.
Castingforreferencetypes
Section9.10.
Castingforvaluetypes
Section9.11.
Commontypingwithother.NETlanguages
Chapter10.
C#operators
Section10.1.
OperatorsandtheirprecedenceinC#


Section10.2.
Operatoroverloading
Section10.3.
typeofoperator
Section10.4.
checkedanduncheckedoperatorsandstatements
Section10.5.
The==operator
Section10.6.
Theisoperator(Java'sinstanceofoperator)
Section10.7.
Theasoperator
Chapter11.
Iterationandflowcontrol
Section11.1.
Loopingwiththewhile,do,for,continueandbreakkeywords
Section11.2.
Conditionalstatementsusingtheifandelsekeywords
Section11.3.
Loopingwiththeforeachkeyword
Section11.4.
Conditionalstatementswiththeswitchandcasekeywords
Section11.5.
Flowcontrolwiththebreakandcontinuekeywords
Section11.6.
Flowcontrolwiththegotokeyword


Part4.
Coretopics

Chapter12.
Arrays

Section12.1.
One-dimensionalarrays
Section12.2.
Multi-dimensionalarrays:rectangulararrays
Section12.3.
Multi-dimensionalarrays:jaggedarrays
Section12.4.
Mixingjaggedandrectangulararrays
Section12.5.
UsingtheSystem.Arrayclass
Chapter13.
Exceptionhandling
Section13.1.
Exceptionexamples
Section13.2.
C#exceptionhierarchy
Section13.3.
ExaminingSystem.Exception
Section13.4.
Innerexceptions
Section13.5.
Catchinggenericexceptions


Chapter14.
C#delegates
Section14.1.
Whataredelegates?
Section14.2.
Afirstdelegateexample
Section14.3.
Combiningdelegates
Section14.4.
Removingdelegates
Section14.5.
Exceptionthrowingindelegates
Section14.6.
Passingmethodparametersbyreferenceindelegates
Chapter15.
C#events
Section15.1.
Genericeventmodel
Section15.2.
WhatareC#events?
Section15.3.
Afullexample
Section15.4.
Anotherfullexample
Chapter16.
Reflectionanddynamicmethodinvocation
Section16.1.
Retrievingthetypeofaninstance


Section16.2.
Retrievingthetypefromanameofaclass
Section16.3.
Retrievingmethodsfromatype
Section16.4.
Retrievingmodulesfromanassembly
Section16.5.
Dynamicallyinvokingmethodsinlateboundobjects
Section16.6.
Creatingnewtypesduringruntime
Chapter17.
Multi-threadedprogramming
Section17.1.
Multi-threading
Section17.2.
Threadstatesandmulti-threadinginC#
Section17.3.
Threadsynchronization
Section17.4.
Threadingguidelines
Chapter18.
FileI/O
Section18.1.
Copying,moving,anddeletingfiles
Section18.2.
Copying,moving,anddeletingdirectories
Section18.3.
Readingfromorwritingtoabinaryfile


Section18.4.
Readingfromandwritingtotextfiles

Chapter19.
C#collectionclasses

Section19.1.
ArrayList
Section19.2.
BitArray
Section19.3.
Hashtable
Section19.4.
Queue
Section19.5.
SortedList
Section19.6.
Stack
Part5.
Conveniencefeatures
Chapter20.
C#properties
Section20.1.
Propertiesasareplacementforaccessorandmutatormethods
Section20.2.
Havingonlyeitherthegetorsetsection
Section20.3.
Inheritanceofproperties


Chapter21.
C#indexes
Section21.1.
Overloadingindexers
Section21.2.
Wronguseofindexers
Chapter22.
Operatoroverloading
Section22.1.
Explainingoperatoroverloading
Section22.2.
Operatoroverloadingproper
Section22.3.
Anotherexampleofoperatoroverloading
Chapter23.
User-definedconversions/casts
Section23.1.
Theimplicitandexplicitkeywords
Section23.2.
Syntaxofuser-definedconversionmethoddeclarations
Part6.
C#-specificfeatures
Chapter24.
C#preprocessordirectives
Section24.1.
ConditionalcompilationWith#define,#undef,#ifand#endif
Section24.2.


#elseand#elif
Section24.3.
The/definecompileroptionand#undef
Section24.4.
#warningand#error
Section24.5.
#regionand#endregion
Chapter25.
Usingenums
Section25.1.
Specifyingdifferentintvaluesforenumelements
Chapter26.
C#structures
Section26.1.
Firstlookatstructs
Section26.2.
Differencesbetweenastructandaclass
Section26.3.
Whyuseastruct?
Chapter27.
C#attributes
Section27.1.
Firstlookatattributes
Section27.2.
Standardattributes
Chapter28.
Writingcustomattributes


Section28.1.
Anattributeclass
Section28.2.
Anothercustomattributeexample

Section28.3.
Namingattributeclassesandattributespecifications
Section28.4.
Customattributesindepth
Section28.5.
TheAttributeUsageattribute
Chapter29.
Writingunsafecodes
Section29.1.
Definitions
Section29.2.
ComparingJavaandC#/.NET
Section29.3.
Introducingpointers
Section29.4.
Usingtheunsafekeyword
Section29.5.
Declaringpointers
Section29.6.
Usingthe&address-ofoperator
Section29.7.
Usingthe*Indirectionoperator
Section29.8.


Passingpointerstomethods
Section29.9.
Usingthe->memberaccessoperator
Section29.10.
Usingthesizeofoperator
Section29.11.
Pointercasting
Section29.12.
Pointerarithmetic
Section29.13.
Usingthefixedkeyword
Section29.14.
Afurtherexample
Part7.
Appendices
AppendixA.
KeywordsinC#
AppendixB.
ComparingJavaandC#keywords
AppendixC.
C#codingconventions
SectionC.1.
Generalnamingconventions
SectionC.2.
NamingC#events
SectionC.3.
NamingC#enums


SectionC.4.
NamingC#interfaces
SectionC.5.
NamingC#properties
SectionC.6.
Namingnamespaces
SectionC.7.
Languageinteroperabilityissues
AppendixD.
XMLdocumentation
AppendixE.
C#commandlinetools
AppendixF.
About.NETassemblies
SectionF.1.
Whatisanassembly?
SectionF.2.
SharedassembliesandtheGAC
SectionF.3.
WhatisDLLhell?
SectionF.4.
CreatingDLLassembliesusingcsc.exe
SectionF.5.
Compilingtomodules
SectionF.6.
Referencinganexternalmoduleduringcompilationofanassembly
AppendixG.


Abbreviationsusedinthisbook


Copyright
PEARSONEDUCATIONLIMITED
HeadOffice:
EdinburghGate
HarlowCM202JE
Tel:+44(0)1279623623
Fax:+44(0)1279431059
LondonOffice:
128LongAcre
LondonWC2E9AN
Tel:+44(0)2074472000
Fax:+44(0)2074472170
Website:
www.it-minds.com
www.awprofessional.com
FirstpublishedinGreatBritainin2003
©PearsonEducationLtd2003
TherightofHengNgeeMoktobeidentifiedastheAuthorofthisWork
hasbeenassertedbyhiminaccordancewiththeCopyright,Designsand
PatentsAct1988.
BritishLibraryCataloguinginPublicationDataACIPcataloguerecordfor
thisbookcanbeobtainedfromtheBritishLibraryLibraryofCongress
Cataloging-in-PublicationDataMok,HengNgee.
FromJavatoC#:adeveloper'sguide/HengNgeeMok.
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-321-13622-5(pbk.:alk.paper)
1.Java(Computerprogramlanguage)2.C#(Computerprogram
language)I.Title.


QA76.73.J38M6452003
005.13'3--dc21
2002034461
Allrightsreserved;nopartofthispublicationmaybereproduced,stored
inaretrievalsystem,ortransmittedinanyformorbyanymeans,
electronic,mechanical,photocopying,recording,orotherwisewithout
eitherthepriorwrittenpermissionofthePublishersoralicence
permittingrestrictedcopyingintheUnitedKingdomissuedbythe
CopyrightLicensingAgencyLtd,90TottenhamCourtRoad,LondonW1P
4LP.Thisbookmaynotbelent,resold,hiredoutorotherwisedisposedof
bywayoftradeinanyformofbindingorcoverotherthanthatinwhichit
ispublished,withoutthepriorconsentofthePublishers.
10987654321
TypesetbyMathematicalCompositionSettersLtd,Salisbury,Wiltshire.
PrintedandboundinGreatBritainbyBiddlesLtdofGuildfordandKing's
Lynn.
ThePublishers'policyistousepapermanufacturedfromsustainable
forests.

Dedication
Thisbookgoestomyever-caringMum,andmydarlingSiewLeng.
Notforgettingourdear'fightinghamsters'whoaccompaniedmethrough
thenightwhileIwashackingawayatthecomputer:Hammok,Hammie,
Hamzel,andthelateHammy.


Abouttheauthor
HengNgeeMokisanexperienceddeveloperwhohasbeeninvolvedin
numerouslarge-scalesoftwareenterpriseprojectsbasedonJ2EE.
Besidesdevelopmentwork,HengNgeeholdsadhoctrainingclassesfor
JavaandJ2EEtechnology.HelecturesregularlyatNanyang
Polytechnic'sSchoolofIT,atertiaryinstitutioninSingapore.
HengNgeewritesfrequentlyforComputerTimes,aweeklylocalIT
newspaperandhasbeeninvitedtospeakatMicrosoft'sDeveloper
FestivalandtheofficiallaunchofVisualStudio.NETinSingapore.He
wasawardedMostValuableProfessionalstatusbyMicrosoftAsiaatthe
firstAsiaMVPSummitheldatShanghai.
AswellasbeingaSunCertifiedProgrammerforJava2,aSunCertified
WebComponentDeveloperforJ2EE,andaMicrosoftCertifiedSystems
Engineer,HengNgeeholdsafirstdegreeincomputerengineering,and
iscompletinghisthesisforhispostgraduatedegreeincommunications
softwareandnetworks.
HengNgeelivesincosmopolitanandequatorial(read"warmandhumid")
Singapore.Heenjoysnaturetrekking,lazinginbedwithagoodbook,
tinkeringwiththelatesttechnicaltoys(hecan'tcultivatethishabittothe
fullestbecauseofameagreincome),andpokinghisnoseintoforeign
culturesonbackpackingtrips.Contacthimatmok@ieee.orgbothtooffer
commentsaboutthisbook,orifyouintendtovisithiscountryona
shoestringbudget.


Preface
Myfirstrealcontactwith.NETstartedlatein2001.SinceMarch2000,I
havebeenhostingafortnightlyJava-relatedcolumnsponsoredbySun
Microsystems(Singapore)intheComputerTimes.Afriendfrom
MicrosoftSingaporeapproachedmeandhandedmeaCDcontainingthe
betaversionofVS.NETsothatIcouldtakealookatitand'maybewrite
somethinginteresting'ifIsodesired.
OfcoursebythattimeIhadalreadyheardofthisnewinfrastructurefrom
Microsoft.Microsofthadbeenmarketing.NETaggressivelyforages,and
IhadoncewrittenarelativelysuperficialintroductiontotheC#language.
Atthattime,detailsweresketchyatbestandtherewasn'tevena
prototypeC#compilerthen.
AndsoIgotmyhandsdirtywithVS.NETBeta2.Aftergettingan
understandingofwhat.NETisallabout,Idecidedtopickuponeofthe
severallanguagesthatsupportit.NaturallyC#becamemychoice.In
fact,mypersonalopinionisthatanyonereallyinterestedindeveloping
using.NEThasonlythreechoices:C#,VB.NET,andJ#.Intheoryyou
candevelop.NETapplicationsusinganyofthetwentyorso'.NETenabled'languages(includingmodifiedversionsofEiffelandeven
COBOL).Neverthelessyoucanforgetaboutallexceptthosethatcame
bundledwithVS.NETandaresupportedbyMicrosoft.Isupposeyour
projectmanagerwillnotbeverypleasedifyousubmityour(albeit
working).NETmoduleinCOBOLcodes.
Ofthethree,IchoseC#.Thisisapowerfulobject-orientedlanguagewith
itsrootsinC++andJava.(Officially,C#hasbeentoutedastheoffspring
ofCandC++only.DespitethefactthatJavaisn'tmentionedonceinthe
C#LanguageSpecificationandotherMicrosoftliterature,itisquite
evidentthatthemakersofC#hadindeedstudiedand`inherited´some
featuresfromJava.)WithC#,youcandoanythingthatcanpossiblybe
donewithinthe.NETCLR.VB.NETisasignificantimprovementoverVB
6withtheadditionofrealobject-orientedfeaturessuchasclass
inheritanceandpolymorphicmethodinvocation.Nevertheless,thereare


taskswhichaC#programcandothatarebeyondthereachofaVB
.NETprogram.C#allowsthedevelopertowriteunsafecodes.Youcan't
dothatwithVB.NETorJ#.Thecreatorsof.NEThadwrittenhuge
chunksofthe.NETBCLsusingC#itself.Tome,C#meanslotsofpower,
whileVB.NETisMicrosoft'swayofallowingVB6developerstomigrate
to.NETwithaslittlepainaspossible.J#,ontheotherhand,reeksof
VisualJ++'sfailure.
Learninganewprogramminglanguagefromscratchcanbeanawesome
task.Imaginelearningawholenewdevelopmentplatformormulti-tiered
infrastructure!Nevertheless,itshouldbenotedthatmostparallel(or
competing)technologiesarebasedonsimilarcomputerscience
concepts,anditwillbemucheasiertolearn,say,anewobject-oriented
programminglanguageonceyouhaveagoodfoundationinanother
object-orientedprogramminglanguage(assumingyoureallyunderstand
thefundamentalconceptsbehindobject-orientedtechnology).
Duringmyexperimentationwith.NETBeta,Irealizedthatlearningthe
CLRiseasyifyoualreadyknowwhataJVMis.Similarly,pickingupASP
.NETiseasierifyouhavedoneJSPprogrammingbefore.
AsIwaslearningabout.NET,Icouldn'thelpbutcomparethedifferences
betweenC#andJava,ASP.NETandJSP,theCLRandtheJVM,.NET
andtheJ2EEframework.IamanexperiencedJavadeveloperand
trainer,andasIwasreadingthroughbooksanddocumentation,Icouldn't
helpnoticingthatC#andJavaaresyntacticallyverysimilar.Icouldhave
skippedasignificantportionofthetext-ifonlyIknewwhichsectionsto
skip.
Ididn'twanttoreadabouthowtousetheswitch/casekeywordsinC#
againbecauseIalreadyknewthatfrommyJavaknowledge.AllIwanted
toknowwasthatinC#,switchcantakeinnotonlynumerictypesbut
stringstoo.That'sthedifference,andthat'sallthatIneededtoknowifI
wantedtousetheswitch/casekeywordsinaC#program.Ihadto
readawholeparagraphjusttounderstandonesmallpoint.Ifonlythere
wasabookwhichhighlightedjustthedifferencesbetweenC#andJava!
Laterthatyear,Microsoftinvitedmetoapublicforumandlectureduring


theMicrosoft'sDevelopers'Festival.WhileIwaspreparingmytalk,
entitled'.NETforJavaDevelopers',Imadealisthighlightingthe
differencessyntacticalandotherwisebetweenC#andJava.Eventually
Idecidedtoturnitintoabook(whichyouarereadingnow).
Theobjectiveistoenablethereadertousecurrentknowledgeand
experienceinJavaandJ2EEtopickupC#and.NETconceptsasquickly
aspossible.InsteadofrepeatingwhatIthinkanaverageJavadeveloper
shouldalreadyknow,IwillhighlightthedifferencesbetweenJavaand
C#.ThisbookwillnotexplainwhatanexceptionisalloveragainIshall
zoomstraightintohowC#treatsexceptionsdifferentlyfromJava.
Assuch,thisbookassumesaworkingknowledgeoftheJava
programminglanguage,familiaritywiththeJavasyntax,andexperience
withbasiccodingconceptssuchasexceptionhandlingandobjectorientedprogramming.
Ihavetriedtopresenteachsectionusingclearsimpleexamples[1]that
areshortandtothepoint.Eachsectionismeanttobequiteindependent
ofothers,andwheresuchdependentknowledgeisrequiredto
understandaparticularpoint,Istateso.Ihaveassumedthatitisyour
responsibilitytointegratealltheknowledgegainedintheseparate
sectionstomakeuseofthelanguage'sfeaturesinacomplex
complementaryway.Mycodeexampleswillavoiddoingthatforclarity
purposes.
[1]Haveyoueverseentutorialexampleswhichrequireyoutohaveextensiveknowledge

ofanothertopic?Suchexamplesreallyirritateme.Idon'tliketoreadlongpiecesofcode
justtounderstandasimpleprinciple,andthat'swhyIhavetriedtokeepmycode
examplesshortyetcomprehensive.

Inordernottoclutteruptherealmeatofeachsection,Ihaveplacedmy
personalobservations,comments,andURLswhereyoucanobtainmore
relevantinformationinfootnotes.
IhopeyoufindlearningaboutC#and.NETasenrichinganexperience
asmine.


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

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

×