外文翻译--C#介绍.doc
英文原文IntroducingC#C#-pronounced“SeeSharp”-isaprogramminglanguagedesignedforMicrosofts.NETplatform.Sinceitsfirstreleasein2002,C#hasfoundmanyroles.Itiswidelyusedontheserversideofwebsites,andalsoonboththeclientandserverinline-of-businessWindowsdesktopapplications.YoucanwritesmartphoneuserinterfacesandXbox360gamesinC#.Morerecently,MicrosoftsSilverlightplatformhasmadeC#anoptionforwritingRichInternetApplicationsthatruninawebbrowser.ButwhatkindoflanguageisC#?Tounderstandalanguagewellenoughtouseiteffectively,itsnotenoughtofocuspurelyonthedetailsandmechanisms,althoughwellbespendingplentyoftimeonthoseinthisbook.Itisequallyimportanttounderstandthethinkingbehindthedetails.Sointhischapter,welllookatwhatproblemsC#wasbuilttosolve.Thenwellexplorethestyleofthelanguage,throughaspectsthatdistinguishitfromotherlanguages.AndwellfinishthechapterwithalookatthelateststepintheevolutionofC#,itsfourthversion.WhyC#?Why.NET?Programminglanguagesexisttohelpdevelopersbemoreproductive.Manysuccessfullanguagessimplifyorautomatetedioustasksthatpreviouslyhadtobedonebyhand.Someoffernewtechniquesthatallowoldproblemstobetackledmoreeffectively,oronalargerscalethanbefore.HowmuchdifferenceC#canmaketoyouwilldependonyourprogrammingbackground,ofcourse,soitsworthconsideringwhatsortsofpeoplethelanguagedesignershadinmindwhentheycreatedC#.C#isaimedatdevelopersworkingontheWindowsplatform,anditssyntaxisinstantlyfamiliartousersofCorC+,orotherlanguagesthatdrawfromthesametradition,suchasJavaScriptandJava.Fundamentallanguageelementssuchasstatements,expressions,functiondeclarations,andflowcontrolaremodeledascloselyaspossibleontheirequivalentsinCfamilylanguages.Afamiliarsyntaxisnotenoughofareasontopickalanguage,ofcourse,soC#offersproductivity-enhancingfeaturesnotfoundinsomeofitspredecessors.Garbagecollectionfreesdevelopersfromthetyrannyofcommonmemorymanagementproblemssuchasmemoryleaksandcircularreferences.Verifiabletypesafetyofcompiledcoderulesoutawiderangeofbugsandpotentialsecurityflaws.WhileCorC+Windowsdevelopersmaynotbeaccustomedtothosefeatures,theywillseemoldhattoJavaveterans,butJavahasnothingtocompetewiththe“LINQ”featuresC#offersforworkingwithcollectionsofinformation,whetherinobjectmodels,XMLdocuments,ordatabases.Integratingcodefromexternalcomponentsisremarkablypainless,eventhosewritteninotherlanguages.C#alsoincorporatessupportforfunctionalprogramming,apowerfulfeaturepreviouslymostcommonlyseeninacademiclanguages.ManyofthemostusefulfeaturesavailabletoC#developerscomefromthe.NETFramework,whichprovidestheruntimeenvironmentandlibrariesforC#,andallother.NETlanguages,suchasVB.NET.C#wasdesignedfor.NET,andoneofthemainbenefitsofitscloserelationshipwiththe.NETFrameworkisthatworkingwithframeworkfeaturessuchastheclasslibraryfeelsverynatural.The.NETFrameworkClassLibraryWorkinginC#meansmorethanusingjustthelanguage-theclassesofferedbythe.NETFrameworkareanextremelyimportantpartoftheC#developerseverydayexperience(andtheyaccountforalotofthisbookscontent).Mostofthelibraryfunctionalityfallsintooneofthreecategories:utilityfeatureswrittenin.NET,wrappersaroundWindowsfunctionality,andframeworks.Thefirstgroupcomprisesutilitytypessuchasdictionaries,lists,andothercollectionclasses,aswellasstringmanipulationfacilitiessuchasaregularexpressionengine.Therearealsofeaturesthatoperateonaslightlylargerscale,suchastheobjectmodelsforrepresentingXMLdocuments.SomelibraryfeaturesarewrappersaroundunderlyingOSfunctionality.Forexample,thereareclassesforaccessingthefilesystem,andforusingnetworkfeaturessuchassockets.Andthereareclassesforwritingoutputtotheconsole,whichwecanillustratewiththeobligatoryfirstexampleofanyprogramminglanguagebook,showninExample1-1.Example1-1.Theinevitable“Hello,world”exampleclassProgramstaticvoidMain()System.Console.WriteLine("Hello,world");Wellexamineallthepiecesshownhereinduecourse,butfornow,notethateventhissimplestofexamplesdependsonaclassfromthelibrary-theSystem.Consoleclassinthiscase-todoitsjob.Finally,theclasslibraryofferswholeframeworkstosupportbuildingcertainkindsofapplications.Forexample,WindowsPresentationFoundation(WPF)isaframeworkforbuildingWindowsdesktopsoftware;ASP.NET(whichisnotanacronym,despiteappearances)isaframeworkforbuildingwebapplications.Notallframeworksareaboutuserinterfaces-WindowsCommunicationFoundation(WCF)isdesignedforbuildingservicesaccessedoverthenetworkbyothercomputersystems,forinstance.Thesethreecategoriesarenotstrict,asquiteafewclassesfitintotwo.Forexample,thepartsoftheclasslibrarythatprovideaccesstothefilesystemarenotjustthinwrappersaroundexistingWin32APIs.Theyaddnewobject-orientedabstractions,providingsignificantfunctionalitybeyondthebasicfileI/Oservices,sothesetypesfitintoboththefirstandsecondcategories.Likewise,frameworksusuallyneedtointegratewithunderlyingservicestosomeextentforexample,althoughtheWindowsFormsUIframeworkhasadistinctiveAPIofitsown,alotoftheunderlyingfunctionalityisprovidedbyWin32components.Sothethreecategoriesherearenotstrict.Theyjustofferausefulideaofwhatsortsofthingsyoucanfindintheclasslibraries.LanguageStyleC#isnottheonlylanguagethatrunsonthe.NETFramework.Indeed,supportformultiplelanguageshasalwaysbeenakeyfeatureof.NET,reflectedinthenameofitsruntimeengine,theCLRorCommonLanguageRuntime.Asthisnameimplies,.NETisnotjustforonelanguagenumerouslanguageshaveaccesstotheservicesofthe.NETFrameworkclasslibrary.WhymightyouchooseC#overtheothers?Wealreadymentionedoneimportantreason:C#wasdesignedspecificallyfor.NET.Ifyouareworkingwith.NETtechnologiessuchasWPForASP.NET,youllbespeakingtheirlanguageifyouworkinC#.ComparethiswithC+,whichsupports.NETthroughextensionstotheoriginallanguage.Theextensionsarecarefullythoughtoutandworkwell,butcodethatuses.NETlibrariesjustlooksdifferentfromnormalC+,soprogramsthatbridgetheworldsof.NETandstandardC+neverfeelcompletelycoherent.Andthedualpersonalityoftenpresentsdilemmas-shouldyouusestandardC+collectionclassesortheonesinthe.NETclasslibrary,forexample?Innative.NETlanguagessuchasC#,suchquestionsdonotemerge.F#istheoddoneouthere.Itsafunctionalprogramminglanguage,heavilyinfluencedbyalanguagecalledML.Backin1991,whenyourauthorswerefirst-yearstudents,ouruniversityscomputersciencecoursechoseMLforthefirstprogramminglanguagelecturesinpartbecauseitwassoacademicthatnoneofthestudentswouldpreviouslyhavecomeacrossanythinglikeit.F#isstillattheacademicendofthespectrumdespitehavingclimbedfarenoughdowntheivorytowertobeastandardpartofamainstreamdevelopmentenvironment.Itexcelsatcomplicatedcalculationsandalgorithms,andhassomecharacteristicsthatcanhelpwithparallelexecution.However,aswithmanyfunctionallanguages,thecostofmakingsomehardproblemseasieristhatalotofthingsthatareeasyinmoretraditionallanguagesareremarkablyhardinF#-functionallanguagesareadeptatcomplexproblems,butcanbeclumsywithsimpleones.ItseemslikelythatF#willmostlybeusedinscientificorfinancialapplicationswherethecomplexityofthecomputationtobeperformeddwarfsthecomplexityofthecodethatneedstoactontheresultsofthosecalculations.ManagedCodeThe.NETFrameworkprovidesmorethanjustaclasslibrary.Italsoprovidesservicesinsubtlerwaysthatarenotaccessedexplicitlythroughlibrarycalls.Forexample,earlierwementionedthatC#canautomatesomeaspectsofmemorymanagement,anotorioussourceofbugsinC+code.Abandoningheap-allocatedobjectsonceyouredonewiththemisacodingerrorinC+,butitsthenormalwaytofreethemin.NET.ThisserviceisprovidedbytheCLR-the.NETFrameworksruntimeenvironment.AlthoughtheC#compilerworkscloselywiththeruntimetomakethispossible,providingthenecessaryinformationabouthowyourcodeusesobjectsanddata,itsultimatelytheruntimethatdoestheworkofgarbagecollection.Dependingonwhatsortsoflanguagesyoumayhaveworkedwithbefore,theideathatthelanguagedependsheavilyontheruntimemightseemeithercompletelynaturalorsomewhatdisconcerting.ItscertainlydifferentfromhowCandC+work-withthoselanguages,thecompilersoutputcanbeexecuteddirectlybythecomputer,andalthoughthoselanguageshavesomeruntimeservices,itspossibletowritecodethatcanrunwithoutthem.ButC#codecannotevenexecutewithoutthehelpoftheruntime.Codethatdependsentirelyontheruntimeiscalledmanagedcode.Managedcompilersdonotproducerawexecutablecode.Instead,theyproduceanintermediateformofcodecalledIL,theIntermediateLanguage.Theruntimedecidesexactlyhowtoconvertitintosomethingexecutable.OnepracticalupshotofmanagedcodeisthatacompiledC#programcanrunonboth32-bitand64-bitsystemswithoutmodification,andcanevenrunondifferentprocessorarchitectures-itsoftenpossibleforcodethatrunsonanARM-basedhandhelddevicetorununmodifiedonIntel-basedPCs,oronthePowerPCarchitecturefoundintheXbox360gameconsole.IfyoureaJavadeveloper,allofthiswillsoundratherfamiliarjustsubstitutebytecodeforILandthestoryisverysimilar.Indeed,apopularbutsomewhatignorant“joke”amongthelessthoughtfulmembersoftheJavacommunityistodescribeC#asapoorimitationofJava.WhenthefirstversionofC#appeared,thedifferencesweresubtle,butthefactthatJavawentontocopyseveralfeaturesfromC#illustratesthatC#wasalwaysmorethanamereclone.Thelanguageshavegrownmoreobviouslydifferentwitheachnewversion,butonedifference,presentfromthestart,isparticularlyimportantforWindowsdevelopers:C#hasalwaysmadeiteasytogetatthefeaturesoftheunderlyingWindowsplatform.ContinuityandtheWindowsEcosystemSoftwaredevelopmentplatformsdonotsucceedpurelyontheirownmerits-contextmatters.Forexample,widespreadavailabilityofthird-partycomponentsandtoolscanmakeaplatformsignificantlymorecompelling.Windowsisperhapsthemoststrikingexampleofthisphenomenon.Anynewprogrammingsystemattemptingtogainacceptancehasaconsiderableadvantageifitcanplugintosomeexistingecosystem,andoneofthebiggestdifferencesbetweenC#andJavaisthatC#andthe.NETFrameworkpositivelyembracetheWindowsplatform,whileJavagoesoutofitswaytoinsulatedevelopersfromtheunderlyingOS.While.NEToffersfeaturestoeaseintegrationwiththeunderlyingplatform,thereisstillsupportfornon-Windowssystems.MicrosoftsSilverlightcanrunC#andVB.NETcodeonMac