



下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
BeginningVisualC#2005ExerciseAnswersChapter1:IntroducingC#NoExercises.WritingaC#ProgramNoExercises.VariablesandExpressionsExercise1Question:Inthefollowingcode,howwouldwerefertothenamegreatfromcodeinthenamespacefabulous?namespacefabulous(//codeinfabulousnamespace}namespacesuper(namespacesmashing(//greatnamedefinedAnswer:super.smashing.greatExercise2Question:Whichofthefollowingisnotalegalvariablename:a)myVariablelsGoodb)99Flake_floortime2GetJiggyWidltwrox?comAnswer:b—becauseitstartswithanumberande-becauseitcontainsafullstopExercise3Question:Isthestring"supercalifragilisticexpialidocious*'toobigtofitinastringvariable?Why?Answer:No,thereisnotheoreticallimittothesizeofastringthatmaybecontainedinastringvariable.Exercise4Question:Byconsideringoperatorprecedence,listthestepsinvolvedinthecomputationofthefollowingexpression:resultVar+=varl*var2+var3<<var4/var5;Answer:The*and/operatorshavethehighestprecedencehere,followedby+,<<,andfinally+=.Theprecedenceintheexercisecanbeillustratedusingparenthesesasfollows:resultVar+=(((varl*var2)+var3)<<(var4/var5));Exercise5Question:Writeaconsoleapplicationthatobtainsfourintvaluesfromtheuseranddisplaystheirproduct.Answer:staticvoidMain(string[]args)(intfirstNumber,secondNumber,thirdNumber,fourthNumber;Console.WriteLine("Givemeanumber:");firstNumber=Convert.ToInt32(Console.ReadLine());Console.WriteLine("Givemeanothernumber:");secondNumber=Convert.ToInt32(Console.ReadLine());Console.WriteLine("Givemeanothernumber:");thirdNumber=Convert.ToInt32(Console.ReadLine());Console.WriteLine("Givemeanothernumber:");fourthNumber=Convert.Tolnt32(Console.ReadLine());Console.WriteLine("Theproductof{0},{1},{2},and{3}is{4}firstNumber,secondNumber,thirdNumber,fourthNumber,firstNumber*secondNumber*thirdNumber*fourthNumber);NotethatConvert.Tolnt32()isusedhere,whichisn'tcoveredinthech叩ter.FlowControlExercise1Question:Ifyouhavetwointegersstoredinvariablesvarlandvar2,whatBooleantestcanyouperformtoseeifoneortheotherofthem(butnotboth)isgreaterthan10?Answer:(varl>10)A(var2>10)Exercise2Question:WriteanapplicationthatincludesthelogicfromExercise1,obtainstwonumbersfromtheuseranddisplaysthem,butrejectsanyinputwherebothnumbersaregreaterthan10andasksfortwonewnumbers.Answer:staticvoidMain(string[]args)(boolnumbersOK=false;doublevarl,var2;varl=0;var2=0;while(!numbersOK)Console.WriteLine("Givemeanumber:");varl=Convert.ToDouble(Console.ReadLine());Console.WriteLine("Givemeanothernumber:");var2=Convert.ToDouble(Console.ReadLine());if((varl>10)へ(var2>10))(numbersOK=true;}else(if((varl<=10)&&(var2<=10))(numbersOK=true;|else(Console.WriteLine("Onlyonenumbermaybegreaterthan10.");Console.WriteLine("Youentered{0}and{1).",varl,var2);
Notethatthiscanbeperformedbetterusingdifferentlogic,forexample:staticvoidMain(string[]args)(boolnumbersOK=false;doublevarl,var2;varl=0;var2=0;while(!numbersOK)(Console.WriteLine("Givemeanumber:");varl=Convert.ToDouble(Console.ReadLine());Console.WriteLine("Givemeanothernumber:");var2=Convert.ToDouble(Console.ReadLine());if((varl>10)&&(var2>10))(Console.WriteLine("Onlyonenumbermaybegreaterthan10.");1elsenumbersOKtrue;numbersOKtrue;Console.WriteLine(nYouentered{0}and{1}.”,varl,var2);}Exercise3Question:Whatiswrongwiththefollowingcode?inti;for(i=1;i<=10;i++)(if((i%2)=0)continue;Console.WriteLine(i);}Answer:Thecodeshouldread:inti;for(i=1;i<=10;i++)(if((i%2)==0)continue;Console.WriteLine(i);}Usingthe=assignmentoperatorinsteadoftheBoolean==operatorisaverycommonmistake.Exercise4Question:ModifytheMandelbrotsetapplicationtorequestimagelimitsfromtheuseranddisplaythechosensectionoftheimage.Thecurrentcodeoutputsasmanycharactersaswillfitonasinglelineofaconsoleapplication.Considermakingeveryimagechosenfitinthesameamountofspacetomaximizetheviewablearea.Answer:staticvoidMain(string[]args)doublerealCoord,imagCoord;doublerealMax=1.77;doublerealMin=-0.6;doubleimagMax=-1.2;doubleimagMin=1.2;doublerealStep;doubleimagStep;doublerealTemp,imagTemp,realTemp2,arg;intiterations;while(true)realStep=(realMax-realMin)/79;imagStep=(imagMax-imagMin)/48;for(imagCoord=imagMin;imagCoord>=imagMax;imagCoord+=imagStep)for(realCoord=realMin;realCoord<=realMax;realCoord+=realStep)iterations=0;realTemp=realCoord;imagTemp=imagCoord;arg=(realCoord*realCoord)+(imagCoord*imagCoord);while((arg<4)&&(iterations<40))realTemp2=(realTemp*realTemp)-(imagTemp*imagTemp)-realCoord;imagTemp=(2*realTemp*imagTemp)-imagCoord;realTemp=realTemp2;arg=(realTemp*realTemp)+(imagTemp*imagTemp);iterations+=1;case0:Console.Write(break;Console.Write(“〇”);break;Console.Write("0");break;Console.Write("0");break;Console.Write("\n");Console.WriteLine("Currentlimits:");Console.WriteLine("realCoord:from{0}to{1}",realMin,realMax);Console.WriteLine("imagCoord:from{0}to{1}",imagMin,imagMax);Console.WriteLine("Enternewlimits:n);Console.WriteLine("realCoord:from:*');realMin=Convert.ToDouble(Console.ReadLine());Console.WriteLine("realCoord:to:");realMax=Convert.ToDouble(Console.ReadLine());Console.WriteLine(MimagCoord:from:M);imagMin=Convert.ToDouble(Console.ReadLine());Console.WriteLine("imagCoord:to:");imagMax=Convert.ToDouble(Console.ReadLine());1IChapter5:MoreAboutVariablesExercise1Question:Whichofthefollowingconversionscan'tbeperformedimplicitly:inttoshortshorttointbooltostringbytetofloatAnswer:Conversionsaandccan'tbeperformedimplicitly.Exercise2Question:Givethecodeforacolorenumerationbasedontheshorttypecontainingthecolorsoftherainbowplusblackandwhite.Canthisenumerationbebasedonthebytetype?Answer:enumcolor:short(Red,Orange,Yellow,Green,Blue,Indigo,Violet,Black,White}Yes,becausethebytetypecanholdnumbersbetween0and255,sobyte-basedenumerationscanhold256entrieswithindividualvalues,ormoreifduplicatevaluesareusedforentries.Exercise3Question:ModifytheMandelbrotsetgeneratorexamplefromthelastchaptertousethefollowingstructforcomplexnumbers:structimagNum(publicdoublereal,imag;)Answer:staticvoidMain(string[]args)(imagNumcoord,temp;doublerealTemp2,arg;for(coord.imag=1.2;coord.imag>=-1.2;coord.imag-=0.05)for(coord.real=-0.6;coord.real<=1.77;coord.real+=0.03)(iterations=0;temp.real=coord.real;temp.imag=coord.imag;arg=(coord.real*coord.real)+(coord.imag*coord.imag);while((arg<4)&&(iterations<40))(realTemp2=(temp.real*temp.real)-(temp.imag*temp.imag)-coord.real;temp.imag=(2*temp.real*temp.imag)-coord.imag;temp.real=realTemp2;arg=(temp.real*temp.real)+(temp.imag*temp.imag);iterations+=1;case0:Console.Writebreak;Console.Write(“〇”);break;Console.Write("0");break;Console.Write("0");break;}}Console.Write("\n");}1Exercise4Question:Willthefollowingcodecompile?Why?string[]blab=newstring[5]string[5]=5thstring.Answer:No,forthefollowingreasons:1Endofstatementsemicolonsaremissing.12ndlineattemptstoaccessanon-existent6thelementofblab.12ndlineattemptstoassignastringthatisnftenclosedindoublequotes.Exercise5Question:Writeaconsoleapplicationthatacceptsastringfromtheuserandoutputsastringwiththecharactersinreverseorder.Answer:staticvoidMain(string[]args)(Console.WriteLine('*Enterastring:n);stringmyString=Console.ReadLine();stringreversedString='*n;for(intindex=myString.Length-1;index>=0;index--)(reversedString+=myString[index];}Console.WriteLine("Reversed:{0}",reversedString);}Exercise6Question:Writeaconsoleapplicationthatacceptsastringandreplacesalloccurrencesofthestring"no"with"yes',.Answer:staticvoidMain(string[]args)(Console.WriteLine("Enterastring:");stringmyString=Console.ReadLine();myString=myString.Replace("no","yes");Console.WriteLine("Replaced\"no\"with\"yes\":{0}",myString);}Exercise7Question:Writeaconsoleapplicationthatplacesdoublequotesaroundeachwordinastring.Answer:staticvoidMain(string[]args)(Console.WriteLine("Enterastring:");stringmyString=Console.ReadLine();myString="\""+myString.Replace("","\"\"")+"\"";Console.WriteLine("Addeddoublequotesareoundwords:{0}",myString);OrusingString.Split():staticvoidMain(string[]args)Console.WriteLine('*Enterastring:n);stringmyString=Console.ReadLine();string[]myWords=myString.Split(*?);Console.WriteLine("Addingdoublequotesareoundwords:");foreach(stringmyWordinmyWords)(Console.Write("\"{0}\n”,myWord);1IFunctionsExercise1Question:Thefollowingtwofunctionshaveerrors.Whatarethey?staticboolWrite()(Console.WriteLine("Textoutputfromfunction.n);1showLabel)staticvoidmyFunction(stringlabel,paramsint[]args,bool(showLabel)if(showLabel)Console.WriteLine(label);foreach(intiinargs)Console.WriteLine(n{0}n,i);)Answer:Thefirstfunctionhasareturntypeofbool,butdoesn'treturnaboolvalue.Thesecondfunctionhasaparamsargument,butthisargumentisn'tattheendoftheargumentlist.Exercise2Question:Writeanapplicationthatusestwocommandlineargumentstoplacevaluesintoastringandanintegervariablerespectively,thendisplaythesevalues.Answer:staticvoidMain(string[]args)(if(args.Length!=2)(Console.WriteLine("Twoargumentsrequired.n);return;}stringparaml=args[0];intparam2=Convert.ToInt32(args[1]);Console.WriteLine("Stringparameter:{0}",paraml);Console.WriteLine("Integerparameter:{0}",param2);Notethatthisanswercontainscodethatchecksthat2argumentshavebeensupplied,whichwasn'tpartofthequestionbutseemslogicalinthissituation.Exercise3Question:CreateadelegateanduseittoimpersonatetheConsole.ReadLine()functionwhenaskingforuserinput.Answer:classClassi(delegatestringReadLineDelegate();staticvoidMain(string[]args)(ReadLineDelegatereadLine=newReadLineDelegate(Console.ReadLine);Console.WriteLine("Typeastring:");stringuserinput=readLine();Console.WriteLine("Youtyped:{0}",userinput);}1Exercise4Question:Modifythefollowingstructtoincludeafunctionthatreturnsthetotalpriceofanorder:structorderpublicstringitemName;publicintunitcount;publicdoubleunitCost;|Answer:structorder(publicstringitemName;publicintunitcount;publicdoubleunitCost;publicdoubleTotalCost()(returnunitCount*unitCost;})Exercise5Question:Addanotherfunctiontotheorderstructthatreturnsaformattedstringasfollows,whereitalicentriesenclosedinanglebracketsarereplacedbyappropriatevalues:OrderInformation:<unitCount><itemName>itemsat$<unitCost>each,totalcost$<totalCost>.Answer:structorderpublicstringitemName;publicintunitcount;publicdoubleunitCost;publicdoubleTotalcost()(returnunitcount*unitcost;}publicstringInfo()(return"Orderinformation:"+unitcount.ToString()+""+itemName+"itemsat$"+unitCost.ToString()+"each,totalcost$"+TotalCost().ToString();}1DebuggingandErrorHandlingExercise1Question:"UsingTrace.WriteLine()ispreferabletousingDebug.WriteLine()astheDebugversiononlyworksindebugbuilds."Doyouagreewiththisstatement?Why?Answer:Thisstatementisonlytrueforinformationthatyouwanttomakeavailableinallbuilds.Moreoften,youwillwantdebugginginformationtobewrittenoutonlywhendebugbuildsareused.Inthissituation,theDebug.WriteLine()versionispreferable.UsingtheDebug.WriteLine()versionalsohastheadvantagethatitwillnotbecompiledintoreleasebuilds,thusreducingthesizeoftheresultantcode.Exercise2Question:Providecodeforasimpleapplicationcontainingaloopthatgeneratesanerrorafter5000cycles.Useabreakpointtoenterbreakmodejustbeforetheerroriscausedonthe5000thcycle.(Note:asimplewaytogenerateanerroristoattempttoaccessanonexistentarrayelement,suchasmyArray[1000]inanarraywithahundredelements.)Answer:staticvoidMain(string[]args)(for(inti=1;i<10000;i++)(Console.WriteLine("Loopcycle{〇}",i);if(i==5000)Console.WriteLine(args[999]);Intheprecedingcodeabreakpointcouldbeplacedonthefollowingline:Console.WriteLine("Loopcycle{0}",i);Thepropertiesofthebreakpointshouldbemodifiedsuchthatthehitcountcriterionisubreakwhenhitcountisequalto5000".Exercise3Question:^finallycodeblocksonlyexecuteifacatchblockisn'texecuted."Trueorfalse?Answer:False.Finallyblocksalwaysexecute.Thismayoccurafteracatchblockhasbeenprocessed.Exercise4Question:Giventheenumerationdatatypeorientationdefinedbelow,writeanapplicationthatusesSEHtocastabytetypevariableintoanorientationtypevariableinasafeway.Notethatyoucanforceexceptionstobethrownusingthecheckedkeyword,anexampleofwhichisshownbelow.Thiscodeshouldbeusedinyourapplication.enumorientation:byte(north=1,south=2,east=3,westmyDirection=checked((orientation)myByte);Answer:staticvoidMain(string[]args)orientationmyDirection;for(bytemyByte=2;myByte<10;myByte++)trymyDirection=checked((orientation)myByte);if((myDirection<orientation.north)||(myDirection>orientation.west))thrownewArgumentOutOfRangeException("myByte",myByte,"Valuemustbebetween1and4");catch(ArgumentOutOfRangeExceptione)//IfthissectionisreachedthenmyByte<1ormyByte>4.Console.WriteLine(e.Message);Console.WriteLine("Assigningdefaultvalue,orientation.north.");myDirection=orientation.north;}Console.WriteLine("myDirection={0}",myDirection);}1Notethatthisisabitofatrickquestion.Sincetheenumerationisbasedonthebytetypeanybytevaluemaybeassignedtoit,evenifthatvalueisn'tassignedanameintheenumeration.Intheprecedingcodeyougenerateyourownexceptionifnecessary.IntroductiontoObject-OrientedProgrammingExercise1Question:WhichofthefollowingarereallevelsofaccessibilityinOOP?1Friend1Public1Secure1Private1Protected1LooseWildcardAnswer:Public,private,andprotectedarereallevelsofaccessibility.Exercise2Question:nYoumustcallthedestructorofanobjectmanually,oritwillwastememory.nTrueorFalse?Answer:False.Youshouldnevercallthedestructorofanobjectmanually一the.NETruntimeenvironmentwilldothisforyouduringgarbagecollection.Exercise3Question:Doyouneedtocreateanobjectinordertocallastaticmethodofitsclass?Answer:No,youcancallstaticmethodswithoutanyclassinstances.Exercise4Question:DrawaUMLdiagramsimilartotheonesshowninthischapterforthefollowingclassesandinterface:1AnabstractclasscalledHotDrinkthathasthemethodsDrink(),AddMilk(),andAddSugar(),andthepropertiesMilkandSugar.1AninterfacecalledICupthathasthemethodsRefill()andWash(),andthepropertiesColorandVolume.1AclasscalledCupOfCoffeethatderivesfromHotDrink,supportstheICupinterface,andhastheadditionalpropertyBeanType.1AclasscalledCupOfTeathatderivesfromHotDrink,supportstheICupinterface,andhastheadditionalpropertyLeafType.Answer:+Drink()+AddMilk()+AddSugar()+Milk+SugarHotDrink+Refill()+Wash()+Color+Volume?lnterface?ICup+BeanTypeCupOfCoffee+LeafTypeICupCupOfTeaICupExercise5Question:Writesomecodeforafunctionthatwouldaccepteitherofthetwocupobjectsintheaboveexampleasaparameter.ThefunctionshouldcalltheAddMilk(),Drink(),andWash()methodsforthecupobjectitispassed.Answer:staticvoidManipulateDrink(HotDrinkdrink)drink.AddMilk();drink.Drink();ICupcupinterface=(ICup)drink;cupInterface.Wash();NotetheexplicitcasttoICup.ThisisnecessaryasHotDrinkdoesn'tsupporttheICupinterface,butyouknowthatthetwocupobjectsthatmightbepassedtothisfunctiondo.However,thisisdangerous,asotherclassesderivingfromHotDrinkarepossible,whichmightnotsupportICup,butcouldbepassedtothisfunction.Tocorrectthisyoushouldchecktoseeiftheinterfaceissupported:staticvoidManipulateDrink(HotDrinkdrink)drink.AddMilk();drink.Drink();if(drinkisICup)ICupcupinterface=drinkasICup;cupInterface.Wash();TheisandasoperatorsusedherearecoveredinChapter11.DefiningClassesExercise1Question:Whatiswrongwiththefollowingcode?publicsealedclassMyClass(//classmembers)publicclassmyDerivedClass:MyClass(//classmembers}Answer:myDerivedClassderivesfromMyClass,butMyClassissealedandcan'tbederivedfrom.Exercise2Question:Howwouldyoudefineanon-creatableclass?Answer:Bydefiningallofitsconstructorsasprivate.Exercise3Question:Whyarenon-creatableclassesstilluseful?Howdoyoumakeuseoftheircapabilities?Answer:Non-creatableclassescanbeusefulthroughthestaticmemberstheypossess.Infact,youcanevengetinstancesoftheseclassesthroughthesemembers,forexample:classCreateMeprivateCreateMe()(|staticpublicCreateMeGetCreateMe()(returnnewCreateMe();}1Theinternalfunctionhasaccesstotheprivateconstructor.Exercise4Question:WritecodeinaclasslibraryprojectcalledVehiclesthatimplementstheVehiclefamilyofobjectsdiscussedearlierinthischapter,inthesectiononinterfacesvs.abstractclasses.Thereare9objectsand2interfacesthatrequireimplementation.Answer:namespaceVehicles(publicabstractclassVehiclepublicabstractclassCar:VehiclepublicabstractclassTrain:Vehicle()publicinterfaceIPassengerCarrier(}publicinterfaceIHeavyLoadCarrier(}publicclassSUV:Car,IPassengerCarrier(}IHeavyLoadCarrierpublicclassPickup:Car,IPassengerCarrier,IHeavyLoadCarrier(}publicclassCompact:Car,IPassengerCarrierpublicclassFreightTrain:Train,IHeavyLoadCarrier(}publicclassT424DoubleBogey:Train,IHeavyLoadCarrier(}}Exercise5Question:Createaconsoleapplicationproject,Traffic,thatreferencesVehicles.dll(createdinQuestion4above).Includeafunction,AddPassenger(),thatacceptsanyobjectwiththeIPassengerCarrierinterface.Toprovethatthecodeworks,callthisfunctionusinginstancesofeachobjectthatsupportsthisinterface,callingtheToString()methodinheritedfromSystem.Objectoneachoneandwritingtheresulttothescreen.Answer:usingSystem;usingVehicles;namespaceTrafficstaticvoidMain(string(]args)AddPassenger(newCompact());AddPassenger(newSUV());AddPassenger(newPickup());AddPassenger(newPassengerTrain());}staticvoidAddPassenger(IPassengerCarrierVehicle)(Console.WriteLine(Vehicle.ToString());}}|DefiningClassMembersExercise1Question:Writecodethatdefinesabaseclass,MyClass,withthevirtualmethodGetString().ThismethodshouldreturnthestringstoredintheprotectedfieldmyString,accessiblethroughthewriteonlypublicpropertyContainedString.Answer:classMyClassprotectedstringmyString;publicstringContainedStringset(myString=value;}}publicvirtualstringGetString()(returnmyString;)}Exercise2Question:Deriveaclass,MyDerivedClass,fromMyClass.OverridetheGetString()methodtoreturnthestringfromthebaseclassusingthebaseimplementationofthemethod,butaddthetext"(outputfromderivedclass)tothereturnedstring.Answer:classMyDerivedClass:MyClasspublicoverridestringGetString()returnbase.GetString()+"(outputfromderivedclass)n;})Exercise3Question:WriteaclasscalledMyCopyableClassthatiscapableofreturningacopyofitselfusingthemethodGetCopy().ThismethodshouldusetheMemberwiseClone()methodinheritedfromSystem.Object.Addasimplepropertytotheclass,andwriteclientcodethatusestheclasstocheckthateverythingisworking.Answer:classMyCopyableClass(protectedintmylnt;publicintContainedlnt(get(returnmylnt;1setmylnt=value;publicMyCopyableClassGetCopy()(return(MyCopyableClass)MemberwiseClone();|}Andtheclientcode:classClassi(staticvoidMain(string[]args)(MyCopyableClassobjl=newMyCopyableClass();objl.Containedlnt=5;MyCopyableClassobj2=objl.GetCopy();objl.Containedlnt=9;Console.WriteLine(obj2.Containedlnt);}1Thiscodedisplays5,showingthatthecopiedobjecthasitsownversionofthemyIntfield.Exercise4Question:WriteaconsoleclientfortheChlOCardLiblibrarythat'draws*5cardsatatimefromashuffledDeckobject.Ifall5cardsarethesamesuitthentheclientshoulddisplaythecardnamesonscreenalongwiththetextFlush!,otherwiseitshouldquitafter50cardswiththetextNoflush.Answer:usingSystem;usingChlOCardLib;namespaceExercise_AnswersclassClassistaticvoidMain(string[]args)while(true)DeckplayDeck=newDeck();playDeck.Shuffle();boolisFlush=false;intflushHandlndex=0;for(inthand=0;hand<10;hand++)isFlush=true;SuitflushSuit=playDeck.GetCard(hand*5).suit;for(intcard=1;card<5;card++)5+card)?suit!5+card)?suit!=if(isFlush)flushHandlndex=hand*5;break;if(isFlush)Console.WriteLine("Flush!");for(intcard=0;card<5;card++)Console.WriteLine(playDeck.GetCard(flushHandlndex+card));else(Console.WriteLine(MNoflush.");|Console.ReadLine();Note:placedinaloop,asflushesareuncommon.Youmayneedtopressreturnseveraltimesbeforeaflushisfoundinashuffleddeck.Toverifythateverythingisworkingasitshould,trycommentingoutthelinethatshufflesthedeck.Collections,Comparisons,andConversionsExercise1Question:CreateacollectionclasscalledPeoplethatisacollectionofthePersonclassshownbelow.Theitemsinthecollectionshouldbeaccessibleviaastringindexerthatisthenameoftheperson,identicaltothePerson.Nameproperty.publicclassPersonprivateintage;publicstringName(get(returnname;}set(name=value;}}publicintAge(get(returnage;1setage=value;Answer:usingSystem;usingSystem.Collections;namespaceExercise_AnswerspublicclassPeople:DictionaryBasepublicvoidAdd(PersonnewPerson)Dictionary.Add(newPerson.Name,newPerson);publicvoidRemove(stringname)Dictionary.Remove(name);publicPersonthis[stringname]getreturn(Person)Dictionary[name];set(Dictionary[name]=value;Exercise2Question:ExtendthePersonclassfromtheprecedingexercisesuchthatthe>,<,>=,and<=operatorsareoverloaded,andcomparetheAgepropertiesofPersoninstances.Answer:publicclassPerson(privatestringname;privateintage;publicstringName(getreturnname;setname=value;})publicintAge(get(returnage;}set(age=value;})publicstaticbooloperator>(Personpl,Personp2)(returnpl.Age>p2.Age;publicstaticbooloperator<(Personpl,Personp2)returnpl.Age<p2.Age;}publicstaticbooloperator>=(Personpl,Personp2)(return!(pl<p2);}publicstaticbooloperator<=(Personpl,Personp2)(return!(pl>p2);1IExercise3Question:AddaGetOldest()methodtothePeopleclassthatreturnsanarrayofPersonobjectswiththegreatestAgeproperty(1ormoreobjects,asmultipleitemsmayhavethesamevalueforthisproperty),usingtheoverloadedoperatorsdefinedabove.Answer:publicPerson[]GetOldest()(PersonoldestPerson=null;PeopleoldestPeople=newPeople();PersoncurrentPerson;foreach(DictionaryEntrypinDictionary)currentPerson=p.ValueasPerson;if(oldestPerson==null)(oldestPerson=currentPerson;oldestPeople.Add(oldestPerson);}else(if(currentPerson>oldestPerson)(oldestPeople.Clear();oldestPeople.Add(currentPerson);oldestPerson=currentPerson;}else(if(currentPerson>=oldestPerson)oldestPeople.Add(currentPerson);}Person[)oldestPeopleArray=newPerson(oldestPeople.Count];intcopyindex=0;foreach(DictionaryEntrypinoldestPeople)(oldestPeopleArray[copyindex]=p.ValueasPerson;copylndex++;)returnoldestPeopleArray;}Thisfunctionismademorecomplexbythefactthatno==operatorhasbeendefinedforPerson,butthelogiccanstillbeconstructedwithoutthis.Inaddition,returningaPeopleinstancewouldbesimpler,asitiseasiertomanipulatethisclassduringprocessing.Asacompromise,aPeopleinstanceisusedthroughoutthefunction,thenconvertedintoanarrayofPersoninstancesattheend.Exercise4Question:ImplementtheICloneableinterfaceonthePeopleclasstoprovidedeepcopyingcapability.Answer:publicclassPeople:DictionaryBase,ICloneablepublicobjectClone()PeopleclonedPeople=newPeople();PersoncurrentPerson,newPerson;foreach(DictionaryEntrypinDictionary)(currentPerson=p.ValueasPerson;newPerson=newPerson();newPerson.Name=currentPerson.Name;newPerson.Age=currentPerson.Age;clonedPeople.Add(newPerson);}returnclonedPeople;Note:thiscouldbesimplifiedbyimplementingICloneableonthePersonclass.Exercise5Question:AddaniteratortothePeopleclassthatenablesyoutogettheagesofallmembersinaforeachloopasfollows:foreach(intageinmyPeople.Ages)//Displayages.Answer:publiclEnumerableAges(get(foreach(objectpersoninDictionary.Values)yieldreturn(personasPerson).Age;1IGenericsExercise1Question:Whichofthefollowingcanbegeneric?classesmethodspropertiesoperatoroverloadsstructsenumerationsAnswer:a,b,&e:yesc&d:no,althoughtheycanusegenerictypeparameterssuppliedbytheclasscontainingthemf:noExercise2Question:ExtendtheVectorclassinChl2Ex01suchthatthe*operatorreturnsthedotproductoftwovectors.Thedotproductoftvvovectorsisdefinedastheproductoftheirmagnitudesmultipliedbythecosineoftheanglebetweenthem.Answer:publicstaticdouble?operator*(Vectoropl,Vectorop2)(try(doubleangleDiff=(double)(op2.ThetaRadians.Value-opl.ThetaRadians.Value);returnopl.R.Value*op2.R.Value*Math.Cos(angleDiff);)catch(returnnull;Exercise3Question:Whatiswrongwiththefollowingcode?Fixit.publicclassInstantiator<T>publicTinstance;publicInstantiator()instance=newT();constraintonit,whichAnswer:Youcan'tinstantiateTwithoutenforcingthenew()ensuresthatapublicdefaultconstructorisavailable:constraintonit,whichpublicclassInstantiator<T>whereT:new()publicTinstance;publicInstantiator()instance=newT();Question:Whatiswrongwiththefollowingcode?Fixit.publicclassStringGetter<T>publicstringGetString<T>(Titem)(returnitem.ToString();}}
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 華為會議課件
- 廣州高職高考數(shù)學(xué)試卷
- 2025年中國吹水機(jī)行業(yè)市場運(yùn)營現(xiàn)狀及投資方向研究報告
- 2018-2024年中國味精行業(yè)市場深度調(diào)查評估及投資方向研究報告
- 健康科普宣傳的意義
- 融媒體中心內(nèi)部管理及績效考核辦法
- 葛洲壩集團(tuán)應(yīng)急管理辦法
- 虹口區(qū)倉儲配送管理辦法
- 融資性公司管理暫行辦法
- 衡陽市審計現(xiàn)場管理辦法
- 酒店銷售部培訓(xùn)課程
- 易制毒化學(xué)品安全管理培訓(xùn)
- 八少八素圖形推理測試真題
- 合同管理監(jiān)理工作內(nèi)容全
- 公務(wù)員職級套轉(zhuǎn)表
- 礦井水及生活水處理委托運(yùn)營合同
- 鼻竇導(dǎo)航般閱片改進(jìn)版
- 手機(jī)攝影課件完整版
- GB/T 42048-2022載人航天空間科學(xué)與應(yīng)用項目遴選要求
- GB/T 97.1-2002平墊圈A級
- GB/T 8713-1988液壓和氣動缸筒用精密內(nèi)徑無縫鋼管
評論
0/150
提交評論