C# 编程语言概述外文文献翻译_第1页
C# 编程语言概述外文文献翻译_第2页
C# 编程语言概述外文文献翻译_第3页
C# 编程语言概述外文文献翻译_第4页
C# 编程语言概述外文文献翻译_第5页
已阅读5页,还剩28页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C#编程语言概述外文文献翻译(含:英文原文及中文译文)文献出处:BarnettM.C#ProgrammingLanguageOverview[J]LectureNotesinComputerScience,2016,3(4):49-59.英文原文C#ProgrammingLanguageOverviewBarnettM1.HistoryofC,C++,C#TheC#programminglanguageisbasedonthespiritoftheCandC++programminglanguages.Thisaccounthaspowerfulfeaturesandaneasy-to-learncurve.ItcannotbesaidthatC#isthesameasCandC++,butbecauseC#isbuiltonboth,Microsofthasremovedsomefeaturesthathavebecomemoreburdensome,suchaspointers.ThissectionlooksatCandC++andtrackstheirdevelopmentinC#.TheCprogramminglanguagewasoriginallydefinedintheUNIXoperatingsystem.Inthepast,weoftenwrotesomeUNIXapplications,includingaCcompiler,andfinallyusedtowriteUNIXitself.Itisgenerallyacceptedthatthisacademiccompetitionextendstotheworldthatcontainsthisbusiness.TheoriginalWindowsAPIwasdefinedtoworkwithCusingWindowscode,anduntilnowatleastthecoreWindowsoperatingsystemAPISmaintainstheCcompiler.Fromadefinedpointofview,Clacksasingledetail,likethelanguageSmalltalkdoes,andtheconceptofanobject.Youwilllearnmoreaboutthecontentsoftheobject.InChapter8,"WriteObject-OrientedCode,"anobjectiscollectedasadatasetandsomeoperationsareset.ThecodecanbecompletedbyC,buttheconceptoftheobjectcannotbeForcedtoappearinthislanguage.Ifyouwanttoconstructyourcodetomakeitlikeanobject,that'sfine.Ifyoudon'twanttodothis,Cwillreallynotmind.Theobjectisnotanintrinsicpart.Manypeopleinthislanguagedidnotspendalotoftimeinthisprogramexample.Whenthedevelopmentofobject-orientedperspectivesbegantogainacceptance,thinkaboutthecodeapproach.C++wasdevelopedtoincludethisimprovement.ItisdefinedtobecompatiblewithC(justasallCprogramsarealsoC++programsandcanbecompiledbyaC++compiler)ThemainadditiontotheC++languageistoprovidethisnewconcept.C++additionallyprovidesaderivativeoftheclass(objecttemplate)behavior.TheC++languageisamodifiedversionoftheClanguage.Unfamiliar,infrequentlanguages​​suchasVB,C,andC++areverylow-levelandrequirealotofcodingtomakeyourapplicationrunwell.Reasonanderrorchecking.AndC++canbehandledinsomeverypowerfulapplications,thecodeworksverysmoothly.ThegoalissettomaintaincompatibilitywithC.C++cannotbreakthelow-levelfeaturesofC.MicrosoftdefinedC#retainsalotofCandC++statements.Thecodecanalsowanttoidentifythecodequickly.AbigadvantageforC#isthatitsdesignersdidnotmakeitcompatiblewithCandC++.Whenthismayseemlikeawrongtreatment,itisactuallygoodnews.C#eliminatessomethingthatmakesCandC++difficulttoworkwith.BeginningwithquirksanddefectsfoundinC.C#isstartingacleanslateanddoesnothaveanycompatibilityrequirements.SoitcanmaintainthestrengthsofitspredecessorsanddiscardweaknessesthatmakeCandC++programsdifficulttosurvive.2.IntroduceC#C#,thenewlanguageintroducedinthe.NETsystem,isderivedfromC++.However,C#isapopular,object-oriented(frombeginningtoend)type-safelanguage.LanguagefeaturesThefollowingsectionprovidesaquickperspectiveonsomeofthefeaturesoftheC#language.Ifsomeofthemareunfamiliartoyou,don'tworry,everythingwillbeexplainedindetailinthefollowingsections.InC#,allcodeanddatamustbeattachedtoaclass.Youcannotdefineavariableoutsidetheclass,norcanyouwriteanycodethatisnotintheclass.Whenaclassobjectiscreatedandrun,theclassisconstructed.Whentheobjectoftheclassisreleased,theclassisdestroyed.Theclassprovidessingleinheritance,andalltheclasseseventuallygetfromthebaseclassistheobject.Overtime,C#providesversionedtechniquestohelpwiththeformationofyourclassestomaintaincodecompatibilitywhenyouusecodefromyourearlierclasses.Let'slookatanexampleofaclasscalledFamily.Thisclasscontainstwostaticfieldstoholdthefirstandlastnamesoffamilymembers.Inthesameway,thereisawaytoreturnthefullnameofafamilymember.ClassClass1{PublicstringFirstName;PublicstringLastName;PublicstringFullName(){}ReturnFirstName+LastName;}Note:SingleinheritancemeansthataC#classcanonlyinheritfromabaseclass.C#isacollectionthatyoucanpackageyourclassintoanamespacecalledthenamespaceclass.Andyoucanhelparrangecollectionofclassesonlogicalaggregations.WhenyoustartedlearningC#,itwasclearthatallnamespaceswererelatedto.NETtypesystems.MicrosoftalsochosetoincludechannelsthatassistinthecompatibilityofpreviouscodeandAPIs.TheseclassesarealsoincludedinMicrosoft'snamespace.TypeofdataC#letsyouworkwithtwotypesofdata:valuetypesandreferencetypes.Thevaluetypeholdstheactualvalue.Thereferencetypesavestheactualvaluestoredelsewhereinthememory.Rawdatatypes,suchascharacter,integer,float,enumeration,andstructuretypes,areallvaluetypes.Objectsandarraytypesaretreatedasreferencetypes.C#predefinesreferencetypes(objectsandstrings)New,Byte,UnsignedShort,UnsignedInteger,UnsignedLong,Float,Double-Float,Boolean,Character,andThevaluetypeandreferencetypeofthedecimaltypewilleventuallybeexecutedbyaprimitivetypeobject.C#alsoallowsyoutoconvertavalueoratypetoanothervalueoratype.Youcanuseanimplicitconversionstrategyoranexplicitconversionstrategy.Implicitconversionstrategiesarealwayssuccessfulanddonotloseanyinformation(forexample,youcanconvertanintegertoalongintegerwithoutlosinganyinformationbecauselongintegersarelongerthanintegers)Somedataislostbecauselongintegerscanholdmorevaluethanintegers.Conversionoccurs.BeforeandafterreferenceRefertoChapter3"WorkingwithVariables"tofindoutmoreaboutexplicitandimplicitconversionstrategies.Youcanusesingle-dimensionalandmultidimensionalarraysinC#atthesametime.Multidimensionalarrayscanbecomeamatrix.Whenthismatrixhasthesameareasizeasamultidimensionalarray.Orjagged,whensomearrayshavedifferentsizes.Classesandstructurescanhavedatamemberscalledattributesandfields.YoucandefineastructurecalledEmployee.Forexample,thereisafieldcalledName.IfyoudefineanEmployeetypevariablecalledCurrenrEmployee,youcanretrievetheemployee'snamebywritingCurrentEmployee.Name.Whatshouldhappenafterthecodeassignment?Iftheemployee'snamemustbereadbyadatabase,forexample,youcanwriteacode"Whensomepeopleaskforthevalueofthenameattribute,readthenamefromthedatabaseandreturnthenamewiththestringtype".FunctionAfunctionisacodethatcanbeusedatanytime,code.AnexampleofafunctionwillappearearlierthantheFullNamefunction,inthischapter,intheFamilyclass.Afunctionisusuallycombinedwithsomecodethatreturnsinformation,andamethodusuallydoesnotreturninformation.However,forus,wegenerallyattributethemtofunctions.Thefunctioncanhavefourparameters:•Theinputparametershavevalues​​passedintothefunction,butthefunctioncannotchangetheirvalues.•Theoutputparametershavenovaluewhentheyarepassedtothefunction,butthefunctioncangivethemavalueandpassthevaluebacktoitscaller.,•Thereferenceparameterpassesanothervaluebyreference.Theyhaveavalueintothefunction,andthisvaluecanbechangedinthefunction.•Theparameterparameterdefinesanarrayvariableinthelist.C#andCLRworktogethertoprovideautomaticstoragemanagement.Or"Leaveenoughspaceforthisobjecttouse"codelikethis.TheCLRmonitorsyourmemoryusageandautomaticallyretrievesitwhenyouneedit.C#providesalargenumberofoperatorsthatallowyoutowritealargenumberofmathematicalandbitwiseexpressions.Many(butnotall)ofthemcanberedefined,andyoucanchangethejoboftheseoperators.C#providesalonglistofreportsthatyoucandefinethroughavarietyofprocessingpathsthroughyourcode.Throughthereport'soperations,usingkeywordslikeswitch,while,for,break,andcontinueenablesyourcodetobesplitintodifferentpathsdependingonthevalueofthevariable.Classescancontaincodeanddata.Visibilityofeachmembertootherobjects.C#providessuchaccessiblerangesaspublic,protected,internal,protectedinternal,andprivate.VariableVariablescanbedefinedasconstants.Theconstanthasafixedvalueandcannotbechangedduringtheexecutionofyourcode.ThevalueofPI,forexample,isagoodexampleofaconstantbecausehervaluewillnotbechangedwhileyourcodeisrunning.Theenumerationtypedefinesaspecificnamefortheconstant.Forexample,youcandefineanenumeratedtypeofplanetusingMercuryVinyourcode.Ifyouuseavariabletorepresenttheplanet,usingthenamesofthisenumtypecanmakeyourcodeeasiertoread.C#providesanembeddedmechanismtodefineandhandlesomeevents.Ifyouwriteaclassthatperformsalongoperation,youmaywanttocallanevent.Whentheeventends,theclientcansignthistimeandgrabtheeventintheirowncode,hecanletthembenotifiedWhenyouhavecompletedthislongbudget,thiseventhandlingmechanismusesdelegatesinC#,avariablethatreferencesafunction.Note:Eventprocessingisaprograminyourcodethatdetermineswhatactionwilltakeplacewhenatimeoccurs.Forexample,theuserclicksonabutton.Ifyourclassholdsavalue,writesomecodecalledaprotractorthatyourclasscanbeaccessedasifitwereanarray.SupposeyouwriteaclasscalledRainbow.Forexample,itcontainsasetofcolorsinthisrainbow.VisitorsmaywantsomeMYRainbowtoretrievethefirstcolorintherainbow.YoucanwriteanindexerinyourRainbowclasstodefinewhatwillbereturnedwhenthevisitoraccessesyourclassasifitwereanarrayofvalues.InterfaceC#providesaninterfacethataggregatesproperties,methods,andeventsthatdescribeasetoffunctions.TheclassofC#canexecutetheinterface.Ittellstheuserthroughtheinterfaceasetoffunctionfilesprovidedbythisclass.Whatexistingcodecanhaveasfewcompatibilityissuesaspossible.Oncetherewasaninterfaceexposed,itcouldnotbechanged,butitcouldevolvethroughinheritance.C#classescanperformmanyinterfaces,eveniftheclasscanonlyinheritfromabaseclass.Let'slookatanexampleofaveryclearruleintherealworldofC#thathelpsillustratetheinterface.Manyapplicationsusetheadditionsprovidedtoday.Thereistheabilitytoreadadditionalitemswhenexecuted.Todothis,thisaddeditemmustfollowsomerules.DLLadditemsmustdisplayafunctioncalledCEEntry.AndyoumustuseCEdasthebeginningoftheDLLfilename.Whenwerunourcode,itscansthedirectoriesofalltheDLLsthatarestartingwithCEd.Whenitfindsone,itisread.ThenitusesGetProcAddresstofindtheCEEntryfunctionintheDLL.Thisprovesthatitisnecessaryforyoutoobeyalltherulestoestablishanaddition.Thiskindofcreatingareadadditionisnecessarybecauseitcarriesmoreunnecessarycoderesponsibility.Ifweuseaninterfaceinthisexample,yourDLLadditionscanbeappliedtoaninterface.Thisensuresthatallnecessarymethods,properties,andeventsappearintheDLLandarespecifiedasfiles.AttributesTheattributedeclaresadditionalinformationaboutyourclassfortheCLR.Inthepast,ifyouwantedtodescribeyourclassesyourself,youwouldhavetouseafewdecentralizedwaystostoretheminexternalfiles,suchasIDLoreventHTMLfiles.Throughyourefforts,thepropertysolvesthisproblem.Thedeveloperhasconstrainedsomeinformationintheclassandanykindofinformation,forexample,intheclass,defineshowitactswhenitisused.Thepossibilitiesareendless,whichiswhyMicrosoftwillcontainalotofpredefinedattributesinthe.NETframework.CompileC#RunningyourC#codegeneratestwoimportanttypesofinformationthroughtheC#compiler:codeandmetadata.Thenextsectiondescribesthesetwotopicsandcompletesabinaryreviewbuilton.NETcode,whichisassembly.MicrosoftIntermediateLanguage(MSIL)ThecodeoutputbytheC#compileriswritteninanintermediatelanguagecalledMicrosoft.MSILisyourcodethatisusedtoconstructadetailedsetofinstructionstoguideyouonhowtoperform.Itcontainsinstructionsforoperations,suchasinitializationofvariables,methodsforevokingobjects,errorhandling,anddeclaringsomethingnew.C#isnotjustalanguagefromtheMSILsourcecodethatchangesduringthewritingprocess.All.NET-compatiblelanguages,includingVB.NETandC++management,generateMSILwhentheirsourcecodeiscompiled.All.NETlanguages​​usethesameruntime,socodefromdifferentlanguages​​anddifferentcompilerscaneasilyworktogether.ForphysicalCPUs,MISLisnotasetofexplicitinstructions.Itdoesn'tknowanythingaboutyourmachine'sCPU,andyourmachinedoesn'tknowanythingaboutMSIL.Then,whenyourCPUcan'treadMSIL,explainthecode.Thissinkingiscalledjustenoughtowrite,orJIT.ThejoboftheJITcompileristotranslateyouruniversalMSILcodetothemachinesothattheCPUcanexecuteyourcode.Youmaywanttoknowwhatanextrastepisintheprocess.WhenacompilercanimmediatelygenerateCPU-interpretedcodeforwhyMSILwasgenerated,thecompilerdoesthislater.Therearemanyreasonsforthis.First,MSILmakesiteasierforyoutowritecodeasitmovestoadifferentpieceofhardware.SupposeyouhavewrittensomeC#codeandyouwantittorunonyourdesktopandhandhelddevicesatthesametime.ItisverylikelythatthesetwodeviceshavedifferentCPUs.IfyouonlyhaveoneC#compilerwhosegoalisaclearCPU,thenyouneedtwoC#compilers:onewiththedesktopCPUandtheotherwiththehandhelddeviceCPU.Youhavetocompileyourcodetwicetoensurethatyourcorrectcodeisusedontherightdevice.WithMSIL,youonlywriteonce.The.NETFrameworkisinstalledonyourdesktopanditcontainsaJITcompilerthattranslatesyourMSIL-specificCPUcodetoyourmachine.The.NETFrameworkisinstalledonyourhandhelddeviceanditcontainsaJITcompilerthattranslatesthesameMSIL-specificCPU-specificcodetoyourhandhelddevice.TorunMSILcodebaseonanydevicethathasa.NETJITcompiler.YounowhaveonlyoneMSILbasiccodethatcanrunonanydevicethathasa.NETJITcompiler.TheJITcompileronthesedevicescantakecareofyourcodeandmakethemrunsmoothly.AnotherreasonwhythecompilerusesMSIListhatthesettingsoftheinstructioncanbeeasilyreadbyanauthenticatedproximity.Partofthecompiler'sjobistoverifyyourcodetomakeitasclearaspossible.Whenproperlyaccessed,thesechecksensurethatyourcodedoesnotexecuteanyinstructionsthatcancauseyourcodetocrash.ThedefinitionofMSILdirectivesmakesthischeckprocesseasiertounderstand.CPU-specificinstructionsettingsareoptimizedforfastcodeexecution.However,theymakethecodedifficulttoreadandthereforedifficulttocheck.HavingaC#compilerthatcanoutputCPU-specificcodeatoncecanmakecodeinspectiondifficultorevenimpossible.Allowthe.NETFramework'sJITcompilertoverifyyourcodetoensurethatyourcodeaccessesmemorythroughabuggypathandthatthevariabletypesareusedcorrectly.MetadataTheassemblyprocessoutputsthesameamountofmetadata.Thisisaveryimportantpartofthe.NETcodesharingstory.WhetheryouuseC#tobuildaclientapplicationoruseC#tobuildalibrarythatsomepeopleuseforyourapplication,youwillwanttotakeadvantageofsomecompiled.NETcode.ThatcodemayhavebeenprovidedbyMicrosoftaspartofthe.NETframework,oritmaybeprovidedbysomeonlineusers.ThekeytousingaforeigncodeistolettheC#compilerknowthattheclassandthatvariableareinanotherbasecodesothatitcanbefoundintheprecompilationofyourworkandmatchthecodeyouwritewiththesourcecode.Lookatthemetadataforthedirectoryforyourcompiledcode.ThenumberofbitsofsourcecodecompiledbyC#existsinthecompiledcodealongwiththegenerationofMSIL.Thetypesofmethodsandvariablesarecompletelydescribedinthemetadataandarereadytobereadbyotherapplications.Forexample,VB.NETcanreadmetadatafroma.NETlibrarytoprovideintelligentsensingofallthemethodsthatcanbeusedeffectivelyforaparticularclass.IfyouhavealreadyworkedwithCOM,youmaybefamiliarwithtypelibraries.ThegoalofthetypelibraryistoprovidethesamedirectoryfunctionalitytoCOMobjects.However,thetypelibraryisprovidedfromafewlimitations,andinfactnotalldataaboutthetargetcanbeputintothetypelibrary.Metadatain.NETdoesnothavethisdisadvantage.Allthecodeusedtodescribetheclass'sinformationisplacedinthemetadata.memberSometimesyouneedtouseC#tobuildaterminalapplication.Theseapplicationsarepackagedintoanexecutablefileanduse.EXEasanextension.C#completelysupportsthecreationof.EXEfiles.However,therearealsotimeswhenyoudonotwanttobeusedinotherprograms.YoumaywanttocreatesomeusefulC#classes,suchasaVB.NETdeveloperwhowantstouseyourclassinaVB.NETapplication.Inthiscase,youwillnotcreateanapplication,insteadyouwillbuildacomponent.Acomponentisametadatapackage.Asaunittoconfigure,theseclasseswillsharethesamelevelofversioncontrol,securityinformation,anddynamicrequirements.ThinkofacomponentasalogicalDLL.IfyouarefamiliarwithMicrosoft'stranslationservicesorCOM+,thenyoucanthinkofcomponentsasequivalentto.NETpackages.Therearetwokindsofcomponents:privatecomponentsandglobalcomponents.Whenyoubuildyourowncomponent,youdon'tneedtospecifywhetheryouwanttocreateaglobalcomponentoraprivatecomponent.Youcanonlymakeyourcodeaccessiblebyaseparateapplication.YourcomponentisapackagesimilartoaDLLandisinstalledintothesamedirectorywhenyourapplicationrunsit.Theapplicationisonlyexecutablewhenitisinthesamedirectoryasyourcomponent.Ifyouwanttoshareyourcode,moreglobalcomponentsinmoreapplications.Globalcomponentscanbeusedbyanysystem's.NETapplicationregardlessofthedirectoryinwhichitisinstalled.Microsoftinstallscomponentsaspartofthe.NETstructure,andeachMicrosoftcomponentisinstalledasaglobalcomponent.TheMicrosoftArchitectureSDKcontainsthepublicfunctionalitytoinstallandremoveartifactsfromglobalwidgetstorage.C#canbeviewedtosomeextentasaprogramminglanguageforthe.NETWindows-orientedenvironment.Inthepasttenyears,althoughVBandC++havefinallybecomeverypowerfullanguages,someofthecontenthascome.ForVisualBasic,itsmainadvantageisthatitiseasytounderstand.ManyprogrammingtasksareeasytoaccomplishandbasicallyhidetheconnotationsoftheWindowsAPIandtheCOMcomponentstructure.ThedownsideisthatVisualBasichasneverimplementedanearlyversionofobject-oriented,real-world(BASICisprimarilyintendedtomakebeginnerseasiertounderstandthantowritelargecommercialapplications),soitcannotreallybestructuredorobject-oriented.Programminglanguage.Ontheotherhand,C++hasitsownrootintheANSIC++languagedefinition.ItisnotfullycompatiblewithANSIbecauseMicrosoftwrotetheC++compilerbeforetheANSIdefinitionwasstandardized,butitisalreadyquiteclose.Unfortunately,thisleadstotwoproblems.First,ANSIC++wasdevelopedundertechnicalconditionsmorethanadecadeago,soitdoesnotsupportcurrentconcepts(suchasUnicodestringsandgeneratingXMLdocuments),andsomeoftheoldergrammaticalstructuresweredesignedforpreviouscompilers(Forexample,thedeclarationanddefinitionofmemberfunctionsareseparate.)Second,MicrosoftalsotriedtoevolveC++intoalanguageforperforminghigh-performancetasksonWindows-avoidingtheadditionoflargenumbersofMicrosoft-specifickeywordsandlibrariesinthelanguage.TheresultisthatinWindows,thelanguagebecomesaverymessylanguage.LetaC++developertalkabouthowmanystringsaredefinedinthisway:char*,LPTSTR,(MFCversion),CString(WTLversion),wchar_t*,OLECHAR*,andsoon.Nowenteringthe.NETera-anewenvironment,ithasmadenewextensionstobothlanguages.MicrosoftaddedmanyMicrosoft-specifickeywordstoC++andevolvedVBtoVB.NET,retainingsomebasicVBsyntax,butitiscompletelydifferentindesign.Fromapracticalapplicationperspective,VB.NETisaNewlanguage.Here,VisualC#.NET.MicrosoftdescribesC#asasimple,modern,object-oriented,type-safe,andCandC++-derivedprogramminglanguage.Mostindependentcommentatorsare“derivedfromC,C++,andJava”fromtheirclaims.C#isverysimilartoC++andJava.Itusesparentheses({})tomarkblocksofcode,andsemicolonsseparatelinesofstatements.ThefirstimpressionofC#codeisthatitisverysimilartoC++orJavacode.Butaftertheseseemingsimilarities,C#ismucheasiertolearnthanC++butharderthanJava.Itsdesignandmoderndevelopmenttoolsaremoreadaptablethanotherlanguages.ItalsohasVisuaBasic'seaseofuse,highperformance,andlowmemoryaccessibilityofC++.C#includesthefollowingfeatures:●Fullsupportforclassandobject-orientedprogramming,includinginterfaceandinheritance,virtualfunctions,andoperatoroverloading.●Defineacomplete,consistentsetofbasictypes.●Built-insupportforautomaticallygeneratingXMLdocumentdescriptions.●Automaticallycleandynamicallyallocatedmemory.●Classesormethodscanbemarkedwithuser-definedproperties.Thiscanbeusedfordocumentationpurposesandhasacertainimpactoncompilation(forexample,markingamethodtocompileonlywhendebugging).●Fullaccesstothe.NETbaseclasslibraryandeasyaccesstotheWindowsAPI.●Youcanusepointersanddirectmemoryaccess,buttheC#languagecanaccessmemorywithoutthem.●SupportsattributesandeventsinVBstyle.●Changingcompileroptions,ActiveXcontrols(COMcomponents)arecalledbyothercodeinthesameway.●C#canbeusedtowriteASP.NETdynamicWebpagesandXMLWebservices.Itshouldbenotedthatformostofthesefeatures,VB.NETandManagedC++arealsoavailable.ButsinceC#used.NETfromthebeginning,supportfor.NETfeatureswasnotonlycomplete,butalsoprovidedamoresuitablesyntaxthanotherlanguages.TheC#languageitselfisverysimilartoJava,buttherearesomeimprovementsbecauseJavaisnotdesignedforuseina.NETenvironment.Beforeendingthistopic,wemustalsopointouttwolimitationsofC#.Oneisthatthelanguageisnotsuitableforwritingtime-criticalorveryhigh-performancecodes,suchasaloopthatruns1000or1050times,andimmediatelyclearstheresourcestheyoccupywhentheyarenotneeded.Inthisregard,C++maystillbethebestofalllow-levellanguages.ThesecondisthatC#lacksthekeyfunctionsneededforveryhigh-performanceapplications.Theparcelsguaranteeinlininganddestructorfunctionsinspecificareasofthecode.However,suchapplicationsareveryfew.

中文译文C#编程语言概述作者:BarnettM1.C,C++,C#的历史C#程序语言是建立在C和C++程序语言的精神上的。这个账目有着很有力的特征和易学的曲线。不能说C#与C和C++相同,但是因为C#是建立在这两者之上,微软移除了一些成为更多负担的特征,比如说指针。这部分观看C和C++,在C#中追踪它们的发展。C程序语言原本是被定义在UNIX操作系统中的。过去经常编写一些UNIX的应用程序,包括一个C编译器,最后被用于写UNIX自己。它普遍认可在这个学术上的竞争扩展到包含这个商业的世界。最初的WindowsAPI被定义与使用C同Windows代码一起工作,并且直到今天至少设置核心的Windows操作系统APIS保持C编译器。来自一个定义的观点,C缺乏一个细节就像Smalltalk这类语言也包含的一

样,一个对象的概念。你将会学到更多的关于对象的内容在第八章“写面向对象的代码”一个对象作为一个数据的收集并且设置了一些操作,代码可以被C来完成,但是对象的观念并不能被强制出现在这个语言中。如果你想要构造你的代码使之像一个对象,很好。如果你不想这么做,C也确实不会介意。对象并不是一个固有的部分在这门语言中,很多人并没有花很大的经历在这个程序示例中。当面向对象的观点的发展开始得到认可之后,思考代码的方法。C++被开发出,包含了这种改良。它被定义去兼容C(就像所有的C程序同样也是C++程序,并且可以被C++编译器编译)C++语言主要的增加是提供这种新的概念。C++又额外提供了的类(对象的模板)行为的衍生。C++语言是C语言之上的改良体,不熟悉的不常用的语言上,例如VB,C和C++是很底层的,而且需要大量的编码来使你的应用程序很好的运行。理和错误检查。和C++可以处理在一些非常给力的应用程序中,码工作的很流畅。被设定的目标是保持对C的兼容,C++不能够打破C的底层特性。微软定义的C#保留了很多C和C++的语句。码并且能想对快地识别代码。对于C#来说一个很大的优势是它的设计师并没有让它去兼容C和C++。当这看起来或许是个错误的处理时,事实上是一个好消息。C#剔除了一些使得C和C++工作起来很困难的东西。始怪癖和在C中发现的缺陷。C#正在开始一个清洁的石板并且没有任何兼容需求。因此它能够保持前辈的强项并且丢弃使得C和C++程序生存困难的弱点2.引进C#C#这门在.NET体系中被引进的全新语言,是从C++衍生出来的。然而,C#是一门流行的,面向对象的(从头到尾)类型安全的语言。语言特征下面的部分提供了一个快速的视角关于C#语言的一些特征。如果它们中的某些概念对你来说很陌生,不要着急,所有的东西都将在后续章节中详细说明。在C#中,所有的代码和数据都必须被附在一个类中。你不能在类外定义一个变量,同样的你也不能写任何不在类中的代码。当一个类的对象被创建并且运行时,类就被构造了。当类的对象被释放时,类也就被销毁了。类提供了单继承,所有的类最终从基类获取的东西就是对象。随着时间的推移,C#提供了有版本的技术去帮助你的类的形成来保养代码的兼容当你使用你更早期的类的代码的时候。下面让我们来看一个叫做Family的类的例子。这个类包含了两个静态的域来保存家庭成员的第一个名字和最后一个名字。同样的,有一个方法来返回家庭成员的全名。classClass1{publicstringFirstName;publicstringLastName;publicstringFullName(){}returnFirstName+LastName;}注:单继承意味着一个C#类只能从一个基类中继承。C#是你能够打包你的类放到一个被称作namespace类的集合里面。并且可以在逻辑聚合上帮助安排类的收集。当你开始学习C#的时候,很明显所有的namespace都是和.NET类型的系统相关的。微软同样选择包含了一些类辅助于兼容以前的代码和API的通道。这些类同样包含在微软的namespace中。数据类型C#让你使用两种类型的数据工作:值类型和引用类型。值类型保存实际的值。引用类型保存实际的值储存在存储器别处的位置。原始的数据类型,例如字符型,整型,浮点型,枚举型还有结构体类型,这些都是值类型。而对象和数组类型被处理成了引用类型。C#预定义了引用类型(对象和字符串)新,字节,无符号短整型,无符号整型,无符号长整型,浮点型,双精度浮点型,布尔型,字符型和小数类型)的值类型和引用类型最终都会被一个基本类型的对象执行。C#同样允许你将一个值或者一个类型转变为另外一个值或一种类型。你可以使用隐式的转换策略或者显式的转换策略。隐式的转换策略总是成功并且并不丢失任何信息(例如,你可以将一个整型转换为一个长整型而不用丢失任何信息因为长整型比整型长)换策略可能会是你丢失一些数据丢失因为长整型可以比整型保留更多的值)转换发生。前后引用参考第三章“同变量一起工作”来找到更多的关于显式和隐式转换策略的信息。你可以同时使用单维和多维的数组在C#中。多维数组能够变成一个矩阵。当这个矩阵与多维数组有相同的面积大小。或者参差不齐的,当有些数组有不一样的面积大小。类和结构体可以拥有数据成员被称为属性和字段。你可以定义一个叫做Employee的结构体,例如,有一个被称作Name的域,如果你定义了一个Employee类型的变量叫做CurrenrEmployee,你可以通过写CurrentEmployee.Name取回这些雇员的名字。码赋值之后什么应该发生。如果雇员的名字必须被一个数据库读,例如,你可以写一个代码“当一些人询问名字属性的值时,从数据库中读名字,并且返回这个名字用string类型”。函数一个函数是一种可以随时使用的代码,代码。一个函数的例子将会像FullName函数更早的展示的那样,在这一章中,在Family类中。一个函数通常会联合一些返回信息的代码,而一个方法通常不返回信息。然而对于我们而言,我们一般都会把它们都归结于函数。函数可以拥有四种参数:•输入的参数有值传递到函数内,但是函数无法改变它们的值。•输出的参数没有值当他们被传递给函数时,但是函数可以给它们值并且将这个值传回给它的调用者。,•引用参数通过引用传递另外的一个值。它们有一个值进入函数,并且这个值可以在函数中被更改。•参数参数在列表中定义了一个数组变量。C#和CLR一同工作来提供自动的存储管理。或者“留足够的空间让这个对象使用”这样的代码。CLR监视你的内存使用并且自动的取回更逗当你需要它的时候。C#提供了大量的运算符使得你能够写大量的数学和逐位运算的表达式。他们当中的大量(并不是所有)运算符可以被重新定义,是你能够改变这些运算符的工作。C#提供了一个长的报表的清单是你能够定义各种各样的处理路径通过你的代码。通过报表的操作,使用关键字,就像switch,while,for,break

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论