版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 智能餐飲培訓(xùn)課程設(shè)計(jì)
- 旅游專業(yè)托盤課程設(shè)計(jì)
- 2024-2030年卡車和公共汽車后視鏡行業(yè)市場(chǎng)現(xiàn)狀供需分析及重點(diǎn)企業(yè)投資評(píng)估規(guī)劃分析研究報(bào)告
- 2024-2030年北京養(yǎng)老機(jī)構(gòu)行業(yè)發(fā)展動(dòng)態(tài)及前景規(guī)劃研究報(bào)告
- 2024-2030年六氯丙酮搬遷改造項(xiàng)目可行性研究報(bào)告
- 2024-2030年全球機(jī)械密封市場(chǎng)發(fā)展前景與投資風(fēng)險(xiǎn)分析報(bào)告
- 2024-2030年全球及中國(guó)調(diào)酒用糖漿行業(yè)銷售情況及競(jìng)爭(zhēng)前景預(yù)測(cè)報(bào)告
- 2024-2030年全球及中國(guó)聚硅氧烷季銨鹽8行業(yè)產(chǎn)銷需求及投資潛力預(yù)測(cè)報(bào)告
- 2024-2030年全球及中國(guó)瓶裝礦泉水行業(yè)營(yíng)銷態(tài)勢(shì)及投資盈利預(yù)測(cè)報(bào)告
- 2024-2030年全球及中國(guó)涂料助焊劑行業(yè)前景動(dòng)態(tài)及投資趨勢(shì)預(yù)測(cè)報(bào)告
- 電力行業(yè)電力調(diào)度培訓(xùn)
- 生態(tài)安全與國(guó)家安全
- 全力以赴備戰(zhàn)期末-2024-2025學(xué)年上學(xué)期備戰(zhàn)期末考試主題班會(huì)課件
- 2024年保密協(xié)議書(政府機(jī)關(guān))3篇
- 《視頻拍攝與制作:短視頻?商品視頻?直播視頻(第2版)》-課程標(biāo)準(zhǔn)
- 研發(fā)部年終總結(jié)和規(guī)劃
- 醫(yī)學(xué)細(xì)胞生物學(xué)(溫州醫(yī)科大學(xué))知到智慧樹章節(jié)答案
- 中國(guó)古代文學(xué)(三)智慧樹知到期末考試答案章節(jié)答案2024年廣東外語外貿(mào)大學(xué)
- 2024年政府采購(gòu)評(píng)審專家考試題庫(kù)真題(一共十套卷一千道真題)
- 船體結(jié)構(gòu)CM節(jié)點(diǎn)
- 有機(jī)電致發(fā)光發(fā)展歷程及TADF材料的發(fā)展進(jìn)展
評(píng)論
0/150
提交評(píng)論