Tải bản đầy đủ - 0 (trang)
Chapter 9.  Arrays, Indexers, and Collections

Chapter 9.  Arrays, Indexers, and Collections

Tải bản đầy đủ - 0trang

9.1.Arrays

Anarrayisanindexedcollectionofobjects,allofthesame

type.C#arraysaresomewhatdifferentfromarraysinC++

becausetheyareobjects.Thisprovidesthemwithuseful

methodsandproperties.

C#providesnativesyntaxforthedeclarationofArrays.What

isactuallycreated,however,isanobjectoftypeSystem.Array.

[1]

ArraysinC#thusprovideyouwiththebestofbothworlds:

easy-to-useC-stylesyntaxunderpinnedwithanactualclass

definitionsothatinstancesofanarrayhaveaccesstothe

methodsandpropertiesofSystem.Array.Theseappearin

Table9-1.

int[]myArray=newint[5]whatyou

actuallycreateintheILcodeisaninstanceofSystem.int32[],butsincethisderivesfromthe

abstractbaseclassSystem.Array,itisfairtosayyou'vecreatedaninstanceofa

System.Array.

[1]Ofcourse,whenyoucreateanarraywith



Table9-1.System.Arraymethodsandproperties

Methodor

property



Purpose



BinarySearch()



Overloadedpublicstaticmethodthatsearchesaone-dimensionalsorted

array.



Clear()



Publicstaticmethodthatsetsarangeofelementsinthearrayeitherto

0ortoanullreference.



Copy()



Overloadedpublicstaticmethodthatcopiesasectionofonearrayto

anotherarray.



CreateInstance( Overloadedpublicstaticmethodthatinstantiatesanewinstanceofan

)

array.

Overloadedpublicstaticmethodthatreturnstheindex(offset)ofthe



IndexOf()



firstinstanceofavalueinaone-dimensionalarray.



LastIndexOf()



Overloadedpublicstaticmethodthatreturnstheindexofthelast

instanceofavalueinaone-dimensionalarray.



Reverse()



Overloadedpublicstaticmethodthatreversestheorderoftheelements

inaone-dimensionalarray.



Sort()



Overloadedpublicstaticmethodthatsortsthevaluesinaonedimensionalarray.



IsFixedSize



RequiredbecauseArrayimplementsICollection.Witharrays,thiswill

alwaysreturntrue(allarraysareofafixedsize).



IsReadOnly



Publicproperty(requiredbecauseArrayimplementsIList)thatreturns

aBooleanvalueindicatingwhetherthearrayisread-only.



IsSynchronized



Publicproperty(requiredbecauseArrayimplementsICollection)that

returnsaBooleanvalueindicatingwhetherthearrayisthread-safe.



Length



Publicpropertythatreturnsthelengthofthearray.



Rank



Publicpropertythatreturnsthenumberofdimensionsofthearray.



SyncRoot



Publicpropertythatreturnsanobjectthatcanbeusedtosynchronize

accesstothearray.



GetEnumerator(

PublicmethodthatreturnsanIEnumerator.

)



GetLength()



Publicmethodthatreturnsthelengthofthespecifieddimensioninthe

array.



GetLowerBound( Publicmethodthatreturnsthelowerboundaryofthespecified

)

dimensionofthearray.

GetUpperBound( Publicmethodthatreturnstheupperboundaryofthespecified

)

dimensionofthearray.



Initialize()



Initializesallvaluesinavaluetypearraybycallingthedefault

constructorforeachvalue.Withreferencearrays,allelementsinthe

arrayaresettonull.



SetValue()



Overloadedpublicmethodthatsetsthespecifiedarrayelementstoa

value.



9.1.1.DeclaringArrays

DeclareaC#arraywiththefollowingsyntax:

type[]array-name;



Forexample:

int[]myIntArray;



Youaren'tactuallydeclaringanarray.Technically,youaredeclaringa

variable(myIntArray)thatwillholdareferencetoanarrayofintegers.

Asalways,we'llusetheshorthandandrefertomyIntArrayasthe

array,knowingthatwhatwereallymeanisthatitisavariablethat

holdsareferencetoan(unnamed)array.



Thesquarebrackets([])telltheC#compilerthatyouare

declaringanarray,andthetypespecifiesthetypeofthe

elementsitwillcontain.Inthepreviousexample,myIntArrayis

anarrayofintegers.

Instantiateanarrayusingthenewkeyword.Forexample:



myIntArray=newint[5];



Thisdeclarationcreatesandinitializesanarrayoffiveintegers,

allofwhichareinitializedtothevalue0.



VB6programmerstakenote:inC#,thevalueofthesizeofthearray

marksthenumberofelementsinthearray,nottheupperbound.In

fact,thereisnowaytosettheupperorlowerbounds(withthe

exceptionthatyoucansetthelowerboundsinmultidimensionalarrays

(discussedlater),buteventhatisnotsupportedbythe.NET

Frameworkclasslibrary).



Thus,thefirstelementinanarrayis0.ThefollowingC#statement

declaresanarrayof10elements,withindices0through9:



stringmyArray[10];



Theupperboundis9,not10,andyoucan'tchangethesizeofthe

array(thatis,thereisnoequivalenttotheVB6Redimfunction).



Itisimportanttodistinguishbetweenthearrayitself(whichisa

collectionofelements)andtheelementsofthearray.

myIntArrayisthearray(or,moreaccurately,thevariablethat

holdsthereferencetothearray);itselementsarethefive

integersitholds.

C#arraysarereferencetypes,createdontheheap.Thus,the



arraytowhichmyIntArrayrefersisallocatedontheheap.The

elementsofanarrayareallocatedbasedontheirowntype.

Sinceintegersarevaluetypes,theelementsinmyIntArraywill

bevaluetypes,notboxedintegers,andthusalltheelements

willbecreatedinsidetheblockofmemoryallocatedforthe

array.

Theblockofmemoryallocatedtoanarrayofreferencetypes

willcontainreferencestotheactualelements,whichare

themselvescreatedontheheapinmemoryseparatefromthat

allocatedforthearray.



9.1.2.UnderstandingDefaultValues

Whenyoucreateanarrayofvaluetypes,eachelementinitially

containsthedefaultvalueforthetypestoredinthearray(refer

backtoTable4-2).Thestatement:

myIntArray=newint[5];



createsanarrayoffiveintegers,eachofwhosevalueissetto

0,whichisthedefaultvalueforintegertypes.

Unlikewitharraysofvaluetypes,thereferencetypesinan

arrayaren'tinitializedtotheirdefaultvalue.Instead,the

referencesheldinthearrayareinitializedtonull.Ifyouattempt

toaccessanelementinanarrayofreferencetypesbeforeyou

havespecificallyinitializedtheelements,youwillgeneratean

exception.

AssumeyouhavecreatedaButtonclass.Declareanarrayof

Buttonobjectswiththefollowingstatement:

Button[]myButtonArray;



andinstantiatetheactualarraylikethis:

myButtonArray=newButton[3];



Youcanshortenthisto:

Button[]myButtonArray=newButton[3];



Thisstatementdoesn'tcreateanarraywithreferencestothree

Buttonobjects.Instead,thiscreatesthearraymyButtonArray

withthreenullreferences.Tousethisarray,youmustfirst

constructandassigntheButtonobjectsforeachreferencein

thearray.Youcanconstructtheobjectsinaloopthatadds

themonebyonetothearray.



9.1.3.AccessingArrayElements

Accesstheelementsofanarrayusingtheindexoperator([]).

Arraysarezero-based,whichmeansthattheindexofthefirst

elementisalways0inthiscase,myArray[0].

Asexplainedpreviously,arraysareobjectsandthushave

properties.OneofthemoreusefuloftheseisLength,which

tellsyouhowmanyobjectsareinanarray.Arrayobjectscanbe

indexedfrom0toLength-1.Thatis,iftherearefiveelements

inanarray,theirindexesare0,1,2,3,4.

Example9-1illustratesthearrayconceptscoveredsofar.In

thisexample,aclassnamedTestercreatesanarrayof

Employeesandanarrayofintegers,populatestheEmployee



array,andthenprintsthevaluesofboth.



Example9-1.Workingwithanarray

namespaceProgramming_CSharp

{



//asimpleclasstostoreinthearray

publicclassEmployee

{

publicEmployee(intempID)

{

this.empID=empID;

}

publicoverridestringToString()

{

returnempID.ToString();

}

privateintempID;

}

publicclassTester

{

staticvoidMain()

{

int[]intArray;

Employee[]empArray;

intArray=newint[5];

empArray=newEmployee[3];

//populatethearray

for(inti=0;i
{

empArray[i]=newEmployee(i+5);

}





for(inti=0;i
{

Console.WriteLine(intArray[i].ToString());

}

for(inti=0;i
{

Console.WriteLine(empArray[i].ToString());

}

}

}

}

Output:

0

0

0

0

0

5

6

7



TheexamplestartswiththedefinitionofanEmployeeclassthat

implementsaconstructorthattakesasingleintegerparameter.

TheToString()methodinheritedfromObjectisoverriddento

printthevalueoftheEmployeeobject'semployeeID.

Thetestmethoddeclaresandtheninstantiatesapairofarrays.

Theintegerarrayisautomaticallyfilledwithintegerswhose

valuesaresetto0.TheEmployeearraycontentsmustbe

constructedbyhand.

Finally,thecontentsofthearraysareprintedtoensurethat

theyarefilledasintended.Thefiveintegersprinttheirvalue



first,followedbythethreeEmployeeobjects.



9.2.TheforeachStatement

TheforeachloopingstatementisnewtotheCfamilyof

languages,thoughitisalreadywell-knowntoVBprogrammers.

Theforeachstatementallowsyoutoiteratethroughallthe

itemsinanarrayorothercollection,examiningeachitemin

turn.Thesyntaxfortheforeachstatementis:

foreach(typeidentifierinexpression)statement



Thus,youmightupdateExample9-1toreplacethefor

statementsthatiterateoverthecontentsofthepopulatedarray

withforeachstatements,asshowninExample9-2.



Example9-2.Usingforeach

#regionUsingdirectives

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Text;

#endregion

namespaceUsingForEach

{

//asimpleclasstostoreinthearray

publicclassEmployee

{

//asimpleclasstostoreinthearray

publicEmployee(intempID)

{



this.empID=empID;

}

publicoverridestringToString()

{

returnempID.ToString();

}

privateintempID;

}

publicclassTester

{

staticvoidMain()

{

int[]intArray;

Employee[]empArray;

intArray=newint[5];

empArray=newEmployee[3];

//populatethearray

for(inti=0;i
{

empArray[i]=newEmployee(i+5);

}

foreach(intiinintArray)

{

Console.WriteLine(i.ToString());

}

foreach(EmployeeeinempArray)

{

Console.WriteLine(e.ToString());

}

}

}

}

}



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

Chapter 9.  Arrays, Indexers, and Collections

Tải bản đầy đủ ngay(0 tr)

×