C#入门经典课后习题答案_第1页
C#入门经典课后习题答案_第2页
C#入门经典课后习题答案_第3页
C#入门经典课后习题答案_第4页
已阅读5页,还剩74页未读 继续免费阅读

下载本文档

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

文档简介

BeginningVisualC#2005ExerciseAnswersIntroducingC#NoExercises.WritingaC#ProgramNoExercises.VariablesandExpressionsExercise1Question:Inthefollowingcode,howwouldwerefertothenamegreatfromcodeinthenamespacefabulous?namespacefabulous//codeinfabulousnamespace……namespacesmashing//greatnamedefinedAnswer:super.smashing.greatExercise2Question:Whichofthefollowingisnotalegalvariablename:myVariablelsGood99Flake_floortime2GetJiggyWidlte)Answer:b一becauseitstartswithanumberande—becauseitcontainsafullstopExercise3Question:IsthestringMsupercalifragilisticexpialidocious*1toobigtofitinastringvariable?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:M);firstNumber=Convert.ToInt32(Console.ReadLine());Console.WriteLine("Givemeanothernumber:M);secondNumber=Convert.Tolnt32(Console.ReadLine());Console.WriteLine("Givemeanothernumber:M);thirdNumber=Convert.Tolnt32(Console.ReadLine());Console.WriteLine("Givemeanothernumber:M);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'tcoveredinthechapter.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)A(var2>10))numbersOK=true;elseif((varl<=10)&&(var2<=10))numbersOK=true;elseConsole.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.");elsenumbersOK=true;Console.WriteLine("Youentered{0}and{1}.",varl,var2);Exercise3Question:Whatiswrongwiththefollowingctxle?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<=realMaxrealCoord+=realStep)iterations=0;realTemp=realCoord;imagTemp=imagCoord;arg=(realCoord*realCoord)+(imagCoordimagCoord);while((arg<4)&&(iterations<40))(realTemp2=(realTemp*realTemp)-(imagTempimagTemp)-realCoord;imagTemp=(2*realTemp*imagTemp)-imagCoord;realTemp=realTemp2;arg=(realTemp*realTemp)+(imagTemp*imagTemp);iterations+=1;switch(iterations%4)case0:Console.Write(break;Console.Write("0”)break;Console.Write("O")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:");Console.WriteLine("realCoord:from:");realMin=Convert.ToDouble(Console.ReadLine());Console.WriteLine("realCoord:to:");realMax=Convert.ToDouble(Console.ReadLine());Console.WriteLine("imagCoord:from:");imagMin=Convert.ToDouble(Console.ReadLine());Console.WriteLine("imagCoord:to:");imagMax=Convert.ToDouble(Console.ReadLine());Chapter5: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:structimagNumpublicdoublereal,imag;Answer:staticvoidMain(string[]args)(imagNumcoord,temp;doublerealTemp2,arg;intiterations;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.imagcoord.imag);while((arg<4)&&(iterations<40))realTemp2=(temp.real*temp.real)-(temp.imagtemp.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;}switch(iterations%4)(case0:Console.Write(".")break;Console.Write("〇”)break;Console.Write("O")break;Console.Write("0")break;Console.Write("\n")Exercise4Question:Willthefollowingcodecompile?Why?string[]blab=newstring[5]string[5]=5thstring.Answer:No,forthefollowingreasons:Endofstatementsemicolonsaremissing.2ndlineattemptstoaccessanon-existent6thelementofblab.2ndlineattemptstoassignastringthatisn'tenclosedindoublequotes.Exercise5Question:Writeaconsoleapplicationthatacceptsastringfromtheuserandoutputsastringwiththecharactersinreverseorder.Answer:staticvoidMain(string[]args)Console.WriteLine("Enterastring:**);stringmyString=Console.ReadLine();stringreversedString="";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:");stringmyString=Console.ReadLine();string[]myWords=myString.Split(**);Console.WriteLine("Addingdoublequotesareoundwords:");foreach(stringmyWordinmyWords)Console.Write("\"{0}\"",myWord);FunctionsExercise1Question:Thefollowingtwofunctionshaveerrors.Whatarethey?staticboolWrite()(Console.WriteLine("Textoutputfromfunction.staticvoidmyFunction(stringlabel,paramsint[]args,boolshowLabel)if(showLabel)Console.WriteLine(label);foreach(intiinargs)Console.WriteLine("{0}",i);Answer:Thefirstfunctionhasareturntypeofbool,butdoesn'treturnaboolvalue.Thesecondfunctionhasaparamsargument,butthisargumentisn'tattheendoftheargumentlist.Exercise2Question:Writeanapplicationthatusestwocommandlineargumentstoplacevaluesintoastringandanintegervariablerespectively,thendisplaythesevalues.Answer:staticvoidMain(string[]args)if(args.Length!=2)Console.WriteLine("Twoargumentsrequired.");return;stringparaml=args[0];intparam2=Convert.ToInt32(args[1]);Console.WriteLine("Stringparameter:{0}",paraml);Console.WriteLine("Integerparameter:{0}",param2);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);)}Exercise4Question:Modifythefollowingstructtoincludeafunctionthatreturnsthetotalpriceofanorder:structorder(publicstringitemName;publicintunitCount;publicdoubleunitCost;Answer:structorder(publicstringitemName;publicintunitCount;publicdoubleunitCost;publicdoubleTotalcost()(returnunitCount*unitCostExercise5Question: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();DebuggingandErrorHandlingExercise1Question:"UsingTrace.WriteLine()ispreferabletousingDebug.WriteLine()astheDebugversiononlyworksindebugbuilds."Doyouagreewiththisstatement?Why?Answer:Thisstatementisonlytrueforinformationthatyouwanttomakeavailableinallbuilds.Moreoften,youwillwantdebugginginformationtobewrittenoutonlywhendebugbuildsareused.Inthissituation,theDebug.WriteLine()versionispreferable.UsingtheDebug.WriteLine()versionalsohastheadvantagethatitwillnotbecompiledintoreleasebuilds,thusreducingthesizeoftheresultantcode.Exercise2Question:Providecodeforasimpleapplicationcontainingaloopthatgeneratesanerrorafter5(X)0cycles.Useabreakpointtoenterbreakmodejustbeforetheerroriscausedonthe50(X)thcycle.(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);Thepropertiesofthebreakpointshouldbemodifiedsuchthatthehitcountcriterionis"breakwhenhitcountisequalto5000".Exercise3Question:"finallycodeblocksonlyexecuteifacatchblockisn'texecuted."Trueorfalse?Answer:False.Finallyblocksalwaysexecute.Thismayoccurafteracatchblockhasbeenprocessed.Exercise4Question:Giventheenumerationdatatypeorientationdefinedbelow,writeanapplicationthatusesSEHtocastabytetypevariableintoanorientationtypevariableinasafeway.Notethatyoucanforceexceptionstobethrownusingthecheckedkeyword,anexampleofwhichisshownbelow.Thiscodeshouldbeusedinyourapplication.enumorientation:bytenorth=1,south=2feast=3,west=4myDirection=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(MmyByteM,myByte,"Valuemustbebetween1and4");catch(ArgumentOutOfRangeExceptione)//IfthissectionisreachedthenmyByte<1ormyByte>Console.WriteLine(e.Message);Console.WriteLine("Assigningdefaultvalue,orientation.north.");myDirection=orientation.north;Console.WriteLine("myDirection={0}",myDirection);一:……一…anybytevaluemaybeassignedtoit,evenifthatvalueisn'tassignedanameintheenumeration.Intheprecedingcodeyougenerateyourownexceptionifnecessary.IntroductiontoObject-OrientedProgrammingExercise1Question:WhichofthefollowingarereallevelsofaccessibilityinOOP?FriendPublicSecurePrivateProtectedLooseWildcardAnswer:Public,private,andprotectedarereallevelsofaccessibility.Exercise2Question:"Youmustcallthedestructorofanobjectmanually,oritwillwastememory."TrueorFalse?Answer:False.Youshouldnevercallthedestructorofanobjectmanually—the.NETruntimeenvironmentwilldothisforyouduringgarbagecollection.Exercise3Question:Doyouneedtocreateanobjectinordertocallastaticmethodofitsclass?Answer:No,youcancallstaticmethodswithoutanyclassinstances.Exercise4Question:DrawaUMLdiagramsimilartotheonesshowninthischapterforthefollowingclassesandinterface:AnabstractclasscalledHotDrinkthathasthemethodsDrink(),AddMilk()tandAddSugar(),andthepropertiesMilkandSugar.AninterfacecalledICupthathasthemethodsRefill()andWash(),andthepropertiesColorandVolume.AclasscalledCupOfCoffeethatderivesfromHotDrink,supportstheICupinterface,andhastheadditionalpropertyBeanType.AclasscalledCupOfTeathatderivesfromHotDrink,supportstheICupinterface,andhastheadditionalpropertyLeafType.Answer:Exercise5Question: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();TheisandasoperatorsusedherearccoveredinChapter11.DefiningClassesExercise1Question:Whatiswrongwiththefollowingctxle?publicsealedclassMyClass//classmembersサ“…一…』//classmembers___derivedfrom.Exercise2Question:Howwouldyoudefineanon-creatableclass?Answer:Bydefiningallofitsconstructorsasprivate.Exercise3Question:Whyarenon-creatableclassesstilluseful?Howdoyoumakeuseoftheircapabilities?Answer:Non-creatableclassescanbeusefulthroughthestaticmemberstheypossess.Infact,youcanevengetinstancesoftheseclassesthroughthesemembers,forexample:classCreateMeprivateCreateMe()staticpublicCreateMeGetCreateMe()returnnewCreateMe();Theinternalfunctionhasaccesstotheprivateconstructor.Exercise4Question:WritecodeinaclasslibraryprojectcalledVehiclesthatimplementstheVehiclefamilyofobjectsdiscussedearlierinthischapter,inthesectiononinterfacesvs.abstractclasses.Thereare9objectsand2interfacesthatrequireimplementation.Answer:namespace Vehiclespublic abstractclassVehiclepublic abstractclassCar:Vehiclepublic abstractclassTrain:Vehiclepublic interfaceIPassengerCarrierpublic interfaceIHeavyLoadcarrierpublicclassSUV:Car,IPassengerCarrierpublicclassPickup:Car,IPassengerCarrier,IHeavyLoadCarrierpublicclassCompact:Car,IPassengerCarrierpublicclassPassenger?rainTrain,IPassengerCarrier}publicclassFreightTrainTrain,IHeavyLoadCarrierpublicclassCompact:Car,IPassengerCarrierpublicclassPassenger?rainTrain,IPassengerCarrier}publicclassFreightTrainTrain,IHeavyLoadCarrierpublicclassT424DoubleBogey:Train,IHeavyLoadCarrierExercise5Question:CreateaconsoleapplicationprojectTraffic,thatreferencesVehicles.dll(createdinQuestion4above).Includeafunction,AddPassenger(),thatacceptsanyobjectwiththeIPassengerCarrierinterface.Toprovethatthecodeworks,callthisfunctionusinginstancesofeachobjectthatsupportsthisinterface,callingtheToString()methodinheritedfromSystem.Objectoneachoneandwritingtheresulttothescreen.Answer:usingSystem;usingVehicles;namespaceTrafficclassClassistaticvoidMain(string[]args)AddPassenger(newAddPassenger(newAddPassenger(newAddPassenger(newCompact())AddPassenger(newAddPassenger(newAddPassenger(newAddPassenger(newCompact());SUV());Pickup());PassengerTrain());staticvoidAddPassenger(IPassengerCarrierVehicle)Console.WriteLine(Vehicle.ToString());DefiningClassMembersExercise1Question:Writecodethatdefinesabaseclass,MyClass,withthevirtualmethodGetString().ThismethodshouldreturnthestringstoredintheprotectedfieldmyString,accessiblethroughthewriteonlypublicpropertyContainedStringAnswer:classMyClass(protectedstringmyString;publicstringContainedString(set(myString=value;publicvirtualstringGetString()(returnmyString;Exercise2Question:Deriveaclass,MyDerivedClass,fromMyClass.OverridetheGetString()methodtoreturnthestringfromthebaseclassusingthebaseimplementationofthemethod,butaddthetextH(outputfromderivedclass)tothereturnedstring.Answer:classMyDerivedClass:MyClass(publicoverridestringGetString()(returnbase.GetString()+(outputfromderivedclass)*,;Exercise3Question:WriteaclasscalledMyCopyableClassthatiscapableofreturningacopyofitselfusingthemethodGetCopy().ThismethodshouldusetheMemberwiseClone()methodinheritedfromSystem.Object.Addasimplepropertytotheclass,andwriteclientcodethatusestheclasstocheckthateverythingisworking.Answer:classMyCopyableClass(protectedintmyInt;publicintContainedlnt(get(returnmylnt;)set(mylnt=value;publicMyCopyableClassGetCopy()return(MyCopyableClass)MemberwiseClone()Andtheclientcode:classClassistaticvoidMain(string[]args)MyCopyableClassobjl=newMyCopyableClass()objl.Containedlnt=5;MyCopyableClassobj2=objl.GetCopy();objl.Containedlnt=9;Console.WriteLine(obj2.Containedlnt);Thiscodedisplays5,showingthatthecopiedobjecthasitsownversionofthemylntfield.Exercise4Question:WriteaconsoleclientfortheChlOCardLiblibrarythat'draws*5cardsatatimefromashuffledDeckobject.Ifall5cardsarethesamesuitthentheclientshoulddisplaythecardnamesonscreenalongwiththetextFlush!,otherwiseitshouldquitafter50cardswiththetextNoflush.Answer:usingSystem;usingChlOCardLib;namespaceExercise_Answers(classClassi(staticvoidMain(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++)(if(playDeck.GetCard(hand*5+card).suit!=flushsuit)(isFlush=false;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.n);}Console.ReadLine();Note:placedinaloop,asflushesareuncommon.Youmayneedtopressreturnseveraltimesbeforeaflushisfoundinashuffleddeck.Toverifythateverythingisworkingasitshould,trycommentingoutthelinethatshufflesthedeck.Collections,Comparisons,andConversionsExercise1Question:CreateacollectionclasscalledPeoplethatisacollectionofthePersonclassshownbelow.Theitemsinthecollectionshouldbeaccessibleviaastringindexerthatisthenameoftheperson,identicaltothePerson.Nameproperty.publicclassPersonprivatestringname;privateintage;publicstringNamegetreturnname;setname=value;publicintAgegetreturnage;setage=value;usingSystem;usingSystem.Collections;namespaceExercise_AnswerspublicclassPeople:DietionaryBasepublicvoidAdd(PersonnewPerson)Dictionary.Add(newPerson.Name,newPerson);publicvoidRemove(stringname)Dictionary.Remove(name);publicPersonthis[stringname]getreturn(Person)Dictionary[name];setDictionary[name]=value;「Question:ExtendthePersonclassfromtheprecedingexercisesuchthatthe>,<»>=,and<=operatorsareoverloaded,andcomparetheAgepropertiesofPersoninstances.Answer:publicclassPersonprivatestringname;privateintage;publicstringNamegetreturnname;setname=value;publicintAgegetreturnage;setage=value;

publicstaticboolreturnpl.Age>}operator>(Personpl,p2.Age;Personp2)publicstaticboolreturnpl.Age>}operator>(Personpl,p2.Age;Personp2)publicstaticbooloperator<(Personpl,Personp2)(returnpl.Age<p2.Age;?publicstaticbooloperator>=(Personpl,Personp2)(return!(pl<p2);publicstaticbooloperator<=(Personpl,Personp2)(return!(pl>p2);}Exercise3Question:AddaGetOldest()melhodtothePeopleclassthatreturnsanarrayofPersonobjectswiththegreatestAgeproperty(1ormoreobjects,asmultipleitemsmayhavethesamevalueforthisproperty),usingtheoverloadedoperatorsdefinedabove.Answer:publicPerson[]GetOldest()PersonoldestPerson=null;PeopleoldestPeople=newPeople();PersoncurrentPerson;foreach(DictionaryEntrypinDictionary)currentPerson=p.ValueasPerson;if(oldestPerson==null)oldestPerson=currentPerson;oldestPeople.Add(oldestPerson);elseif(currentPerson>oldestPerson)oldestPeople.Clear();oldestPeople.Add(currentPerson);oldestPerson=currentPerson;elseif(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:DietionaryBase,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;GenericsExercise1Question:Whichofthefollowingcanbegeneric?classesmethodspropertiesoperatoroverloadsstructsenumerationsAnswer:a.b,&e:yesc&d:no,althoughtheycanusegenerictypeparameterssuppliedbytheclasscontainingthemf:noExercise2Question:ExtendtheVectorclassinChl2Ex01suchthatthe*operatorreturnsthedotproductoftwovectors.Thedotproductoftwovectorsisdefinedastheproductoftheirmagnitudesmultipliedbythecosineoftheanglebetweenthem.Answer:publicstaticdouble?operator*(Vectoropl,Vectorop2)trydoubleangleDiff=(double)(op2.ThetaRadians.Value-opl.ThetaRadians.Value);returnopl.R.Value*op2.R.Value*Math.Cos(angleDiff)catchreturnnull;Question:Whatiswrongwiththefollowingcode?Fixit.publicclassInstantiator<T>publicTinstance;publicInstantiator()instance=newT();…ensuresthatapublicdefaultconstructorisavailable:publicclassInstantiator<T>whereT:new()publicTinstance;publicInstantiator()instance=newT();Question:Whatiswrongwiththefollowingcode?Fixit.publicclassStringGetter<T>publicstringGetString<T>(Titem)returnitem.ToString();Answer:Thesamegenerictypeparameter,T,isusedonboththegenericclassandgenericmethod.Youneedtorenameoneorboth,forexample:publicclassStringGetter<U>(publicstringGetString<T>(Titem)(returnitem.ToString();Exercise5Question:CreateagenericclasscalledShortCollection<T>thatimplementsIList<T>andconsistsofacollectionofitemswithamaximumsize.

温馨提示

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

评论

0/150

提交评论