



版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
C#LanguageReferenceOwners: AndersHejlsbergandScottWiltamuthFile: C#LanguageReference.docLastsaved: 1/2/2013Lastprinted:1/2/2013Version0.17b
NoticeThisdocumentationisanearlyreleaseofthefinaldocumentation,whichmaybechangedsubstantiallypriortofinalcommercialrelease,andisinformationofMicrosoftCorporation.Thisdocumentisprox'idedforinformationalpurposesonlyandMicrosoftmakesnowarranties,eitherexpressorimplied,inthisdocument.Informationinthisdocumentissubjecttochangewithoutnotice.Theentireriskoftheuseortheresultsoftheuseofthisdocumentremainswiththeuser.Complyingwithallapplicablecopyrightlawsistheresponsibilityoftheuser.Withoutlimitingtherightsundercopyright,nopartofthisdoaimentmaybereproduced,storedinorintroducedintoaretrievalsystem,ortransmittedinanyformorbyanymeans(electronic,mechanical,photocopying,recording,orotherwise),orforanypurpose,withouttheexpresswrittenpermissionofMicrosoftCorporation.Microsoftmayhavepatents,patentapplications,trademarks,copyrights,orotherintellectualpropertyrightscoveringsubjectmatterinthisdocument.ExceptasexpresslyprovidedinanywrittenlicenseagreementfromMicrosoft,thefurnishingofthisdocumentdoesnotgiveyouanylicensetothesepatents,trademarks,copyrights,orotherintellectualproperty.Unpublishedwork.?1999-2000MicrosoftCorporation.Allrightsreserved.Microsoft,Windows,VisualBasic,andVisualC++areeitherregisteredtrademarksortrademarksofMicrosoftCorporationintheU.S.A,and/orothercountries.Other{productandcompanynamesmentionedhereinmaybethetrademarksoftheirrespectiveowners.TableofContentsTOC\o"1-5"\h\z\o"CurrentDocument"Introduction 1Hello,world 1Automaticmemorymanagement 2\o"CurrentDocument"Types 4Pr^lefinedtypes 5Arraytypes 7Typesystemunification 9Statements 10Statementlistsandblocks 10Labeledstatementsandgotostatements 10Localdeclarationsofconstantsandvariables 11Expressionstatements 11Theifstatement 11Theswitchstatement 12Thewhilestatement 12Thedostatement 13Thefbrstatement 13Theforeachstatement 13Thebreakstatementandthecontinuestatement 14Thereturnstatement 14Thethrowstatement 14Thetrystatement 14Thecheckedanduncheckedstatements 14TheIockstatement 14\o"CurrentDocument"Classes 14\o"CurrentDocument"Structs 15Interfaces 15Delegates 17Enums 18\o"CurrentDocument"Namespaces 18Properties 19Indexers 20Events 21Versioning 22\o"CurrentDocument"Lexicalstructure 27Phasesoftranslation 27Grammarnotation 27Pre-processing 28Pre-processingdeclarations 28#if,#elif,#clse,#endif 29Pre-processingcontrollines 30#line 31Pre-processingidentifiers 31Pre-processingexpressions 31Interactionwithwhitespace 32Lexicalanalysis 33
2.4.5Whitespace 33ProcessingofUnicodecharacterescapesequences 34Literals 362533Reafliterals 37Operatorsandpunctuators 40BasicconceptsMembers Namespacemembers Structmembers Enumerationmembers Classmembers Interfacemembers Arraymembers Delegatemembers Memberaccess Declaredaccessibility Accessibilitydomains Protectedaccess Accessibilityconstraints Signaturesandoverloading Scopes Namehiding Hidingthroughnesting..Hidingthroughinheritan)Namespaceandtypenames Fullyqualifiednames Types Valuetypes Defaultconstructors Structtypes Simpletypes Integraltypes Floatingpointtypes Thedecimaltype Thebooltype Enumerationtypes 4343434444444444444445474849505252535455Referencetypes 4343434444444444444445474849505252535455Classtypes Theobjecttype Thestringtype Interfacetypes Arraytypes Delegatetypes BoxingandunboxingBoxingconversions.UnboxingconversionsTOC\o"1-5"\h\z5.1.2Instancevariables 6Instancevariablesin structs 685.1.5Referenceparameters 68\o"CurrentDocument"6.Conversions 73Implicitconversions 73Identityconversion 73Implicitnumericconversions 73Implicitenumerationconversions 74Implicitreferenceconversions 74Implicitconstantexpressionconversions 74Explicitnumericconversions 75Explicitenumerationconversions 76Unboxingconversions 77User-definedexplicitconversions 77Standardimplicitconversions 77Standardexplicitconversions 786.4User-definedconversions 78Permitteduser-definedconversions 78Evaluationofuser-definedconversions 78User-definedimplicitconversions 79User-definedexplicitconversions 80817.Expressions
81Operatorprecedenceandassociativity * Unaryoperatoroverloadresolution * . Binaryoperatoroverloadresolution Candidateuser-definedoperators Una.rynumericpromotions7.3Memberlookup ■Applicablefunctionmember*."Betteriunetionmember -?????.?l..????.-FunctionmemberinvocationInvocationsonboxedinstances Virtualfunctionmemberlookup Interfacefunctionmemberlookup 7.5.2.Invariantmeaninginblocks Identicalsimplenamesandtypenames Indexeraccess 7.5.8Baseaccess 7.5.9Postfixincrementanddecrementoperators Objectcreationexpressions Arraycreationexpressions Delegatecreationexpressions .13checkedanduncheckedoperators5556667791122234444456688990001122G346788001-888888888.9999999999999999990-000000000000011115556667791122234444456688990001122G346788001-888888888.9999999999999999990-00000000000001111TOC\o"1-5"\h\zBitwisecomplementopemtor IllPrefixincrementanddecrementoperatois. . * * * 1127*6-8C*astexpressions ??<??.?+.?4.+??+.*+.*<?+<?.+?*+**+.+*.+4*+.**.+*.*4.+..*.113Multiplicationoperator 113Divisionoperator 114A?dditionoperator116Subtractionoperator 1177.9Relationaloperators 119Floating-pointcomparisonoperators 121Decimalcomparisonoperators 121Booleanequalityoperators.. 122Enumerationcomparisonoperators 122Referencetypeequalityoperators 122Stringequalityoperators 123Delegateequalityoperators.. 124Theisoperator 1241Integerlogicaloperators 1243Booleanlogicaloperators 125Conditionallogicaloperators... 125Booleanconditionallogicaloperators... 126User-definedconditionallogicaloperatoi's 126Conditionaloperator 127Assignmentoperators 127Constantexpressions 131\o"CurrentDocument"8.Statements 133Endpointsandreachability 133Statementlists 135Labeleustatemeni136DecIsrotionstatements 136Localvariabledeclarations 136Localconstantdeclarations 137Expressionstatements 1388?7SelectionstatementsI38Theifstatement 138Theswitchstatement 139
Iterationstatements Thewhilestatement,... Thedostatement Theforstatement Theforeachstatement... Jumpstatements Thebreakstatement Thecontinuestatement Thegotostatement Thereturnstatement Thethrowstatement Thetrystatement Thecheckedanduncheckedstatements Thelockstatement 9.Namespaces Compilationunits Namespacedeclarations Usingdirectives Usingaliasdiiectives UsingnamespacedirectivesNamespacemembers Typedeclarations…..………1Classmodifiers 1Abstractclasses 2Sealedclasses 2Classbasespecification 1Baseclasses 2Interfaceimplementations 3Classbody Inheritance Thenewmodifier Accessmodifiers Constituenttypes Staticandinstancemembers Nestedtypes 10.4.1Staticandinstancefields... 1Usingstaticreadonlyfieldsforconstants 2Versioningofconstantsandstaticreadonlyfields Fieldinitialization Variableinitializers Staticfieldinitialization 1421431431441451461421431431441451461461471471481491501521525556791155555566333444566778889901222334456666886866666666777777777710.5.2Staticmidinstsnccmethods.. 10.5.4Overridemethods. .……,.………*….………..……… 10.6.3Virtual,override,andabstractaccessors 10.9.3Conversionoperators * Instanceconstructors ConstructorinitializersInstancevariableinitializers Defaultconstructors Privateconstructors Optionalconstructorparameters Destructors 12.1Classloadingandinitialization 7677777878808082838485858586879l93969999ooooa)020203030505()60607081?!tructnioditier??.7677777878808082838485858586879l93969999ooooa)020203030505()6060708Arrays 215Arraytypes. 215TOC\o"1-5"\h\zArrayinitializers 217\o"CurrentDocument"Interfaces 21913.1.2Baseinterfaces 219Interfacemembers 2203.2.3Interfaceevents/ 22224Interfaceindexers 222Fullyqualifiedinterfacemembernames 224Interfaceimplementations 224Explicitinterfacememberimplementations 225Interfacemapping 227Interfaceimplementationinheritance 229Interfacere-implementation 231Abstractclassesandinterfaces 232\o"CurrentDocument"Enums 233Enumdeclarations 233Enumvaluesandoperations 236\o"CurrentDocument"Delegates 237Delegatemodifiers 237\o"CurrentDocument"Exceptions 239\o"CurrentDocument"Attributes 241TheAttributeUsageattribute 241Positionalandnamedparameters 24217.2Attributespecification 24317.3.2Run-timeretrievalofanattributeinstance 24517.4.1TheAttributeUsageattribute 246\o"CurrentDocument"Versioning 251\o"CurrentDocument"Unsafecode 253\o"CurrentDocument"Interoperability 255
Attnbutes TheCOMmportattribute TheCOMSourcelmerface'iattribute TheCOMVisibiIityattribute TheDispIdattribute TheDIIImportattribute TheGlobaIObjectattribute TheGuidattribute TheHasDefaultinterfaceattribute TheImportedFromCOMattribute The1nandOutattributes TheInterfaceTypeattribute TheIsCOMRegisterFunctionattribute TheMarshaIattribute TheNameattribute TheNoIDispatchattribute TheNonSeriaIizedattribute ThePredeclaredattribute TheReiurnsHResultattribute TheSerializableattribute TheSiructLayoutattribute TheSiructOffsetattribute TheTypeLibFuncattribute TheTypeLibTypeattribute TheTypeLibVarattribute 55556677777885555555555555222222222222299900005555667777788555555555555522222222222229990000 12日5556666666662222222222221.IntroductionC#isasimple,modem,objectoriented,andtype-safeprogramminglanguagederivedfromCandC++.C#(pronounced“Csharp")isfirmlyplantedintheCandC++familytreeoflanguages,andwillimmediatelybefamiliartoCandC++programmers.C#aimstocombinethehighproductivityofVisualBasicandtherawpowerofC++.C#isprovidedasapartofMicrosoftVisualStudio7.0.InadditiontoC#,VisualStudiosupportsVisualBasic,VisualC++,andthescriptinglanguagesVBScriptandJScript.AlloftheselanguagesprovideaccesstotheNextGenerationWindowsServices(NWGS)platform,whichincludesacommonexecutionengineandarichclasslibrary.The.NETsoftwaredevelopmentkitdefinesa"CommonLanguageSubset"(CLS),asortoflinguafrancathatensuresseamlessinteroperabilitybetweenCLS-compliantlanguagesandclasslibraries.ForC#developers,thismeansthateventhoughC#isanewlanguage,ithascompleteaccesstothesamerichclasslibrariesthatareusedbyseasonedtoolssuchasVisualBasicandVisualC++.C#itselfdoesnotincludeaclasslibrary.Therestofthischapterdescribestheessentialfeaturesofthelanguage.Whilelaterchaptersdescriberulesandexceptionsinadetail-orientedandsometimesmathematicalmanner,thischapterstrivesforclarityandbrevityattheexpenseofcompleteness.Theintentistoprovidethereaderwithanintroductiontothelanguagethatwillfacilitatethewritingofearlyprogramsandthereadingoflaterchapters.Hello,worldThecanonical4iHello,world"programcanbewritteninC#asfollows:usingSystem:classHeIIoIstaticvoidNfain(){Console.WiteLine("HeIIo,worId");ThedefaultHieextensionforC#programsis.cs,asinhello.es.Suchaprogramcanbecompiledwiththecommandlinedirectiveeschello.eswhichproducesanexecutableprogramnamedhello.exe.Theoutputoftheprogramis:Hei1o,worldCloseexaminationofthisprogramisilluminating:TheusingSystem;directivereferencesanamespacecalledSystemthatisprovidedbythe.NETruntime.ThisnamespacecontainstheConso1eclassreferredtointheMainmethod.Namespacesprovideahierarchicalmeansoforganizingtheelementsofaclasslibrary.A"using“directiveenablesunqualifieduseofthemembersofanamespace.The"Hello,world"programusesConsole.WiieLineasashorthandforSystem.Conso1e.UHteLine.Whatdotheseidentifiersdenote?Systemisanamespace,Consoleisaclassdefinedinthatnamespace,andW-iieLincisastaticmethoddefinedonthatclass.TheNfainfunctionisastaticmemberoftheclassHe11o.Functionsandvariablesarenotsupportedatthegloballevel;suchelementsarealwayscontainedwithintypedeclarations(e.g.,classandstructdeclarations).The"Hello,world“outputisproducedthroughtheuseofaclasslibrary.C#doesnotitselfprovideaclasslibrary.Instead,C#usesacommonclasslibrarythatisalsousedbyotherlanguagessuchasVisualBasicandVisualC++.ForCandC++developers,itisinterestingtonoteafewthingsthatdonotappearinthe“Hello,world''program.Theprogramdoesnotuseeither*'::"or>"operators.The"::"isnotanoperatorinC#atall,andthe>''operatorisusedinonlyasmallfractionofC#programs.C#programsuse"asaseparatorincompoundnamessuchasConso1e.MiteLine.Theprogramdoesnotcontainforwarddeclarations.ForwarddeclarationsarcneverneededinC#programs,asdeclarationorderisnotsignificant.Theprogramdoesnoiuse#incIudetoimportprogramtext.Dependenciesbetweenprogramsarehandledsymbolicallyratherthanwithprogramtext.Thissystemeliminatesbarriersbetweenprogramswrittenindifferentlanguages.Forexample,theConsoleclasscouldbewritteninC#orinsomeotherlanguage.AutomaticmemorymanagementManualmemory'managementrequiresdeveloperstomanagetheallocationandde-allocationofblocksofmemory.Manualmemorymanagementisbothtimeconsuminganddifficult.C#providesautomaticmemorymanagementsothatdevelopersarefreedfromthisburdensometask.Inthevastmajorityofcases,thisautomaticmemorymanagementincreasescodequalityandenhancesdeveloperproductivitywithoutnegativelyimpactingeitherexpressivenessorperformance.TheexampleusingSystem;pubIicclassStackIprivaleNodefirst=null;pubIicboolEmpty(get\return(first==null);publicobjeelPop(){if(first==null)thrownewException("Can1tPopfromanemptyStack.");objecttemp=first.Vaiue;first=first.Next;returntemp;publicvoidPush(objecto){first=newNode(o,first);classNode(publicNodeNext;publicobjectVaiue;publicNode(objeelvalue):this(vaIue,nulI){}publicNode(objectvalue,Nodenext){Next=next;Va1ue=value;}}}showsaStackclassimplementedasalinkedlistofNodeinstances.NodeinstancesarccreatedinthePushmethodandaregarbagecollectedwhennolongerneeded.ANodeinstancebecomeseligibleforgarbagecollectionwhenitisnolongerpossibleforanycodetoaccessit.Forinstance,whenanitemisremovedfromtheStack,theassociatedNodeinstancebecomeseligibleforgarbagecollection.TheexampleclassTestIstaticvoidNfain(){Stacks=newStack();for(inti=0;i<10;i++)s.Push(i);whiIe(!s.Empiy)Console.WileLine($.Pop());})showsatestprogramthatusestheStackclass.AStackiscreatedandinitializedwith10elements,andthenassignedthevaluenull.Oncethevariable$isassignednull,theStackandtheassociated10Nodeinstancesbecomeeligibleforgarbagecollection.Thegarbagecollectorispermittedtocleanupimmediately,butisnotrequiredtodoso.Fordeveloperswhoaregenerallycontentwithautomaticmemorymanagementbutsometimesneedfine-grainedcontrolorthatextraiotaofperformance,C#providestheabilitytowrite“unsafe"code.Suchcodecandealdirectlywithpointertypes,andfixobjectstotemporarilypreventthegarbagecollectorfrommovingthem.This"unsafe"codefeatureisinfact"safe"featurefromtheperspectiveofbothdevelopersandusers.Unsafecodemustbeclearlymarkedinthecodewiththemodifierunsafe,sodeveloperscan'tpossiblyuseunsafefeaturesaccidentally,andtheC#compilerandtheexecutionengineworktogethertoensurethatunsafecodecannotmasqueradeassafecode.TheexampleusingSystem;classTest{1unsafestaticvoid^iteLocations(by(e|]arr){fixed(byte*p_arr=arr)(byte*p_e1em=p.arr;for(inti=0;i<arr.Length;i++){bytevalue=*p_e1em;stringaddr=int.Format((int)p_eIem,"X");ConsoFe.5M,iteLine("arr[{0}]at0x{I}is(2}",i,addr,value);p_e1em++;)staticvoidMiin()|bytcI]arr=newbyte”(1,2,3,4,5};^iteLocations(arr);]}showsanunsafemethodnamed\M-iteLocationsthatfixesanarrayinstanceandusespointermanipulationtoiterateovertheelementsandwriteouttheindex,value,andlocationofeach.Onepossibleoutputoftheprogramis:TOC\o"1-5"\h\zarr[0] at 0x8E0360 i s Iarr[ I] at 0x8E0361 i s 2arr[2) at Ox8E0362 i s 3arr[3] at 0x8E0363 i s 4arr[4] at 0x8E0364 i s 5butofcoursetheexactmemorylocationsaresubjecttochange.1.3TypesC#supportstwomajorkindsoftypes:valuetypesandreferencetypes.Valuetypesincludesimpletypes(e.g.,char,int,andfIoat),enumtypes,andstructtypes.Referencetypesincludeclasstypes,interfacetypes,delegatetypes,andarraytypes.Valuetypesdifferfromreferencetypesinthatvariablesofthevaluetypesdirectlycontaintheirdata,whereasvariablesofthereferencetypesstorereferencestoobjects.Withreferencetypes,itispossiblefortwovariablestoreferencethesameobject,andthuspossibleforoperationsononevariabletoaffecttheobjectreferencedbytheothervariable.Withvaluetypes,thevariableseachhavetheirowncopyofthedata,anditisnotpossibleforoperationsononetoaffecttheother.TheexampleusingSystem;classClassIIpublicintValue=0;)classTestIstaticvoidNiiin(){intvail=0;intvaI2=vail;val2=123;ClassIrefl=newClass1();Class1ref2=ref1;ref2.Value=123;Console.teLine("Values:{0),{I|",vail,val2);Console.WiteLine("Refs:(0),{I}",ref1.Value,ref2,Value);)1showsthisdifference.TheoutputoftheprogramisValues:0,123Refs:123,123TheassignmenttothelocalvariablevalIdoesnotimpactthelocalvariableval2becausebothlocalvariablesareofavaluetype(int)andeachlocalvariableofavaluetypehasitsownstorage.Incontrast,theassignmentref2.Value=123:affectstheobjectthatbothreflandref2reference.Developerscandefinenewvaluetypesthroughenumandstructdeclarations,andcandefinenewreferencetypesviaclass,interface,anddelegatedeclarations.TheexampleusingSystem;pubIicenumColorIRed,Blue,Green}publicstructPointIpublicintx,y;}publicinterface(BaseIvoidF();IpublicinterfaceIDerived:1BaseIvoidG();}publicclassAIprotectedvoidH(){Console.WiteLinc("A.H");})publicclassB:A.1DerivedpublicvoidF()(Console.WiteLine("B.F,impIementationofIDerived.F");}publicvoidG()(Console.ViiteLine("B.G,imp1ementationofIDerived.G");}1publicdelegatevoidEmptyDeIegate();showsanexampleortwotoreachkindoftypedeclaration.Latersectionsdescribetypedeclarationsingreaterdetail.1.4PredefinedtypesC#providesasetofpredefinedtypes,mostofwhichwillbefamiliartoCandC++developers.Thepredefinedreferencetypesareobjeciandstring.Thetypeobjectistheultimatebasetypeofallothertypes.Thepredefinedvaluetypesincludesignedandunsignedintegraltypes,floatingpointtypes,andthetypesboolTchar,anddecimaI.Thesignedintegraltypesaresbyte,short,int,andIong;theunsignedintegraltypesarebyte,ushort.uint,andulong;andthefloatingpointtypesarefIoatanddouble.Thebooltypeisusedtorepresentbooleanvalues:valuesthatareeithertrueorfalse.Theinclusionofboolmakesiteasierfbrdeveloperstowriteself-documentingcode,andalsohelpseliminatetheall-too-commonC++codingerrorinwhichadevelopermistakenlyuseswhenshouldhavebeenused.InC#,theexamplenti=...;F(i);if(i=0) //Bug:thetestshouldbe(i==0)G();isinvalidbecausetheexpressioni=0isoftypeint,andifstatementsrequireanexpressionoftypebool.
ThechartypeisusedtorepresentUnicodecharacters.Avariableoftypecharrepresentsasingle16-bitUnicodecharacter.Thedecimaltypeisappropriateforcalculationsinwhichroundingerrorsareunacceptable.Commonexamplesincludefinancialcalculationssuchastaxcomputationsandcurrencyconversions.Thedecimaltypeprovides28significantdigits.Thetablebelowlistseachofthepredefinedtypes,andprovidesexamplesofeach.TypeDescriptionExamplesobjectTheultimatebasetypeofallothertypesobjecto=newStack();stringStringtype;astringisasequenceofUnicodecharactersstrings="He11o";sbyte8-bitsignedintegraltypesbyteva1=12;short16-bitsignedintegraltypeshortva1=12;int32-bitsignedintegraltypeintva1=12;1ong64-bitsignedintegraltype1ongvail=12;longva12=34L;byte8-bitunsignedintegraltypebytevail=12;byteva12=34U;ushort16-bitunsignedintegraltypeushortval1=12;ushortval2=34U;uint32-bitunsignedintegraltypeuintvail=12;uintva12=34U;ulong64-bitunsignedintegraltypeu1ongvail=12;u1ongva12=34U;u1ongva13=56L:u1ongva14=78UL;floatSingle-precisionfloatingpointtypefloatvalue=1.23F;doub1eDouble-precisionfloatingpointtypedoub1evail=1.23doubleval2=4.56D:boolBooleantype;aboolvalueiseithertrueorfalseboolvalue=true;charCharactertype;acharvalueisaUnicodecharactercharvalue='h';decima1Precisedecimaltypewith28significantdigitsdecimalvalue=I.23MEachofthepredefinedtypesisshorthandforasystem-providedtype.Forexample,thekeywordiniisshorthandforastructnamedSysiem.Int32.Thetwonamescanbeusedinterchangeably,thoughitisconsideredgoodstyletousethekeywordratherthanthecompletesystemtypename.PredefinedvaluetypessuchasinIaretreatedspeciallyinafewwaysbutareforthemostparttreatedexactlylikeotherstructs.Thespecialtreatmentthatthesetypesreceiveincludesliteralsupportandefficientcodegeneration.C#'soperatoroverloadingfeatureenablesdeveloperstodefinetypesthatbehavelikethepredefinedvaluetypes.Forinstance,aDigi(structthatsupportsthesamemathematicaloperationsasthepredefinedintegraltypes,andthatconversiontoandfromthesetypes.usingSystem;structDigitI...IclassTestIstaticvoidTestInt(){inta=1;intb=2;intc=a+b;Console.\^iteLine(c);}staticvoidTestDigit(){Digita=(Digit)1;Digitb=(Digit)2;Digitc=a+b;Console.iteLine(c);)staticvoidMain(){TestInt();TestDigit();})1.5ArraytypesArraysinC#maybesingle-dimensionalormulti-dimensional.Both^rectangulaf'and"jagged“arraysaresupported.Single-dimensionalarraysarethemostcommontype,sothisisagoodstartingpoint.TheexampleusingSystem;classTestIstaticvoidMain(){nt[]arr=newint[5];for(inti=0;i<arr.Length;i++)arr[i|=i*i;for(inti=0;i<arr.Length;i++)Console.WiteLine("arr[{0}]={I}",i,arr[i]);createsasingle-dimensionalarrayofintvalues,initializesthearrayelements,andthenprintseachofthemout.Theprogramoutputis:arr[0]=0arr[4]=I6Thetypein11|usedinthepreviousexampleisanarraytype.Arraytypesarewrittenusinganon-array-typefollowedbyoneormorerankspecifiers.TheexampleclassTestIstaticvoidMsin(){int[]aI; // single-dimensionalarrayof intint[,]a2; 11 2-dimensionalarrayofintintj,,]a3; // 3*dimensionalarrayofintint[][]j2; // "jagged" array: arrayof(arrayof int)int[j[j[]j 3; // arrayof (array of(arrayofint))showsavarietyoflocalvariabledeclarationsthatusearraytypeswithintastheelementtype.Arraysarereferencetypes,andsothedeclarationofanarrayvariablemerelysetsasidespacefbrthereferencetothearray.Arrayinstancesareactuallycreatedviaarrayinitializersandarraycreationexpressions.TheexampleclassTestIstaticvoidMiin()(int[]aI=newint[](1,2,3);int[,]a2=newint[,]]{1,2.3},{4,5,6));int[,f]a3=newintjlO,20,301;nt[1[ ) j2= newi nt[31[J;j2[0j = new i nt[] ( 1, 2, 31;j2[11 = new int(l ( 1, 2, 3, 4, 5, 6);j2[2) = new i nt[] ( 1, 2, 3, 4, 5. 6,7,8,9);showsavarietyofarraycreationexpressions.Thevariablesa1,a2anda3denoterectangulararrays,andthevariablej2denotesajaggedarray.Itshouldbenosurprisethatthesetermsarebasedontheshapesofthearrays.Rectangulararraysalwayshavearectangularshape.Giventhelengthofeachdimensionofthearray,itsrectangularshapeisclear.Forexample,thelengthofa3'sthreedimensionsare10,20,and30respectively,anditiseasytoseethatthisarraycontains1Oa2O,3Oelements.Incontrast,thevariablej2denotesa“jagged“array,oran"arrayofarrays''.Specifically,j2denotesanarrayofanarrayofint,orasingle-dimensionalarrayoftypeint[].Eachoftheseint[]variablescanbeinitializedindividually,andthisallowsthearraytotakeonajaggedshape.Thee
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年河南省安全員考試題庫及答案
- 水處理劑運(yùn)輸協(xié)議
- 2025年度合伙項(xiàng)目退出合同:投資回收與風(fēng)險(xiǎn)承擔(dān)
- 教育培訓(xùn)機(jī)構(gòu)外墻裝修樣本
- 2025年度產(chǎn)品安全召回賠償協(xié)議范本
- 2025年度個(gè)人綠色建筑投資管理協(xié)議
- 2025年度解除終止勞動(dòng)合同后員工離職手續(xù)辦理指南
- 2025年度債權(quán)轉(zhuǎn)讓合同-金融資產(chǎn)重組
- 2025年度員工借調(diào)及數(shù)字化轉(zhuǎn)型合作協(xié)議
- 2025年度廣告?zhèn)髅絼趧?wù)派遣安全服務(wù)協(xié)議
- 心理評(píng)估與診斷簡介
- 無痛病房管理課件
- 讓孩子變成學(xué)習(xí)的天使——由《第56號(hào)教室的奇跡》讀書分享
- 球泡檢驗(yàn)標(biāo)準(zhǔn)
- 公安筆錄模板之詢問嫌疑人(書面?zhèn)鲉局伟舶讣?
- 振動(dòng)分析基礎(chǔ)講義1
- 記賬憑證匯總表excel模板
- 鄧麗君經(jīng)典歌曲30首簡譜(共33頁)
- 故障診斷技術(shù)的國內(nèi)外發(fā)展現(xiàn)狀(共3頁)
- 園林綠化施工通用表格模板
-
評(píng)論
0/150
提交評(píng)論