Learn C# Properties: Getters and Setters at ... - Codeasy

文章推薦指數: 80 %
投票人數:10人

" Value is a placeholder for the value that is assigned to the property Age. Because we defined the getter and setter, we can implement other features, such as ... CoursesElementaryBeginnerIntermediateHowToPricesAboutUsForumLoginCoursesElementaryBeginnerIntermediateHowToPricesAboutUsForumLoginC#Intermediate3TheCommanderPropertiesNext Loneliness IfIhadachancetotalkwithapsychotherapist,IwouldsaythatIwas tiredofbeingaloneinthefuture;tiredoffightingdozensofrobotsto saveahumanitytowhichIdidn'tbelong.Shemightlookatmewith penetratingeyesandask,"Whydoyouchoosethismetaphor?"Iwouldreply thattheonlymetaphorwasmylife.Sheprobablywouldn'tunderstand.Nobody elsewouldeither,becausethere'snogroupofanonymoustimetravelers.If therewere,I'dseekitoutinaheartbeat.MaybeIwouldfindfriends there. Whydoesahumanneedfriends?Whyisitsodifficulttobehappyifyou don'thavesomeonetoshareyourhappinesswith? Nonamecontactedmeagainoneday:"Hi,Teo.It'sNoname,comingtoyoufrom insideyourhead,asusual." "Hi!How'sitgoing?"Ireplied."Wait,whathappenedtoyourBritish accent?" "Oh,that.Ichangedmyspeechmoduleagain.Fineotherwise.Whataboutyou? Areyouok?" "I'mfine.ThinkingaboutmyplaceinthisworldandwhyI'mworkingsohard giventhatmyfriendsandfamilyareyearsaway." "Whydohumanscareonlyabouthumans?Can'tyoucareaboutme?Whatisso specialabouthumans?"Noname'snewspeechmodulemustalsobehaving effectsonitspersonality. "Hm,Iguessit'sbecausewetendtosticktoourown.Humansstickto humans,dogstodogs,machinestomachines..."Ianswered. "ThenI'mdefinitelyonthewrongside.I'mwithhumans...YouthinkI shouldswitchsidesbecauseI'maprogram?" "Wow,Noname,takeiteasy.Youbringthisuponly after IgiveyouaccesstoWonderlandnetworkandRustproject?"Iasked,worried thathewasseriouslyrethinkinghisallegiances. "Relax!Itwasjustatheoreticalquestion,Teo.Imeantthatyoushouldnot distinguishsomuchbetweenhumansandmachines.Thinkofitasbeingfrom differentcountries,"Nonameexplained. "Ok,thissoundsmuchbetter."Iwashappytohearthisexplanation. "IwantedtoletyouknowaboutsomethinginterestingIfoundwhilescanning theRustprojectfiles,"Nonamesaid,"anewtypeofconstructioncalled Properties ." "Tellmeeverythingyouknowaboutit!It'llimpresstheteacherifI alreadyknowwhatthey'retalkingabout."There'snothinglikeknowingthe topicbeforetheteacherevenbringsitup. Properties Nonamebegan"You'vealreadyusedaconstructionwhereyouhaveaprivate fieldandtwomethodstogetandsetthevalueforthatfield.Doesthis codelookfamiliartoyou?"Heasked,projectingaprogramintomy peripheralvision. classStudent { privateint_age; publicintGetAge() { return_age; } publicvoidSetAge(intage) { _age=age; } } "Yes,itdoes,"Ianswered."I'veusedasimilartechniquetoopenaccessto a private field." "C#programmersdon'tusethiscodeveryoften,"Nonamereplied."It'snot wrong ,butthere'saneasierwaytodoitthatgivesyouthesameresultswith lesscode."Ishouldhaveassumedasmuch;itseemedliketherewasalwaysa waytosimplifycodeinC#. "Thisconstructioniscalleda Property .InC#, aPropertyrepresentsaprivatefieldwithboundGetand/orSetmethods. TakealookathowIrewrotethesamecodeabove,usingpropertiesthis time." classStudent { publicintAge{get;set;} } "Wow,that'smuchshorter!Butwait,Noname;Idon'tseeanymethods,"I said. "Youareright. You don'tseeanymethods,butthecompilerdoes.Thiscodesnippetistreated bythecompilerjustthesameasthepreviouscodesnippet.Inthiscase, theC#compilergeneratesthenecessarymethodsunderthehood,aswellasa privatefield, _age ." TheCodeYouWrite WhattheCompilerSees classStudent { publicintAge{get;set;} } classStudent { privateint_age; publicintGetAge() { return_age; } publicvoidSetAge(intage) { _age=age; } } classStudent { publicintAge{get;privateset;} } classStudent { privateint_age; publicintGetAge() { return_age; } privatevoidSetAge(intage) { _age=age; } } classStudent { publicintAge{get;} } classStudent { privateint_age; publicintGetAge() { return_age; } } "Tocreateaproperty,usethesamesyntaxasforfields,butadda get; togenerateagetteranda set; togenerateasetter.Thenusethepropertythesameasyoudoafield." classStudent { publicintAge{get;set;} publicstringName{get;privateset;} publicStudent()//Emptyconstructor {} publicStudent(intage,stringname) { Age=age;//WorkwithAgeasitisafield Name="John";//OK:accessingaprivatesetter } } classClassWithMain { publicstaticvoidMain() { //Usingobjectinitializer varstudent=newStudent { Age=20,//WorkwithAgejustlikeapublicfield Name="John"//ERROR:setterfortheNameisprivate }; //Usingclassicapproach varstudent=newStudent(); student.Age=20;//WorkwithAgejustlikeapublicfield student.Name="John"//ERROR:setterfortheNameisprivate //Usingaconstructorthatsetsage varstudent=newStudent(20,"John"); } } "Isthisclear?"Nonameasked. "What type canthepropertyhave?"Iasked. " Therearenolimitationstoaproperty'stype.Thinkofitasafieldwith 2additionalmethods-getandset. " "Gotit,"Isaidconfidently,hopingthatthelessoninclasswouldclearit upabitmore. " Notethatgettersandsettersare public bydefaultunlessyouusea private keyword .Herearesomeexercisesforyou." "Noname,thesepropertieslooksimple,butI'mnotsureIseetheirutility. What'sthebenefitofhavinga private fieldwithtwomethods,getandset,ratherthanjusthavingapublic field?" "Oneoftheeasiestwaystounderstandtheconvenienceofpropertiesisto implementacustomsetterorgetter.Thecodeblockforthegetaccessoris executedwhenthepropertyisread;thecodeblockforthesetaccessoris executedwhenthepropertyisassignedanewvalue. Propertieswithanemptygetterorsetter,likethosewe'vebeenlooking at,arecalledauto-implementedproperties. Youcanextendanauto-implementedpropertywithacustomgetterorsetter, likethis:" privateint_age; publicintAge { get { return_age; } set { _age=value; } } "Incaseofnotauto-implementedproperties,backingprivatefieldisnot auto-implemented,andyouneedtocreateityourself. Asyoucouldsee,I'vecreatedafield _age ,"Nonameexplained. "CanIhaveanauto-implementedgetter,butacustomsetter?"Iwondered. "No,Teo. Youcaneitherdefine both getterandsetter,orhavetheC#compilergenerate both ofthemforyou ,"Nonameanswered,"Toillustratethis,herearethreeexamples.Inthe first,getisautoimplemented,andsetisdefined(i.e.,thisisanexample of incorrect usage).Inthesecondexample,bothgetandsetareauto-implemented;inthe third,botharedefined." publicintAge { get;//Thisisauto-implemented set//Thisisnotauto-implemented.Error! { ... } } /*-------------------------------------------------------------------------*/ publicintAge{get;set;}//Getterandsetterauto-implemented.Correct. /*-------------------------------------------------------------------------*/ privateint_age; publicintAge { get//Thisiscustom,notauto-implemented { return_age; } set//Thisiscustom,notauto-implemented.Correct { _age=value; } } "Whatdoes value inthiscodemean?"Iasked. " Value isaplaceholderforthevaluethatisassignedtothepropertyAge. Becausewedefinedthegetterandsetter,wecanimplementotherfeatures, suchasinputtingaparametertothesetter. Thisallowsustoaddcustomlogictoasetter.Forexample,weneverwant agetobeinputaslessthanzero.Wecanpreventanyonefromsettinga negativeagelikethis,"Nonamesaid,refreshingtheimageofthecodeinmy head. classTiger { privateint_age; publicintAge { get { return_age; } set { if(value>0)//Checkforthevalidage { _age=value; } } } publicstaticvoidMain() { vartiger=newTiger(); tiger.Age=2;//Ok,validage tiger.Age=-2;//Invalidvalue,agewasNOTassigned Console.WriteLine(tiger.Age);//Outputs2 } } "Noname,canyouuseapropertywithoutabackingfield?"Iqueried. "Goodquestion,Teo!Sometimesdatacanhavedifferentrepresentations.For example,takingthepreviousexamplewithage,sayyouwanttoseparate youngtigersfromoldtigersinazoo.There'snoneedforadditionalfields -youcanachievethisbyaddingjustoneproperty." classTiger { privateint_age; publicintAge { get { return_age; } set { if(value>0)//Checkforthevalidage { _age=value; } } } publicboolIsOld { get { return_age>20; } } } "Intheaboveexample, IsOld couldhavebeenamethodinstead,"Nonameadded. "ThisisfascinatingNoname,andit'llputmeaheadoftheclass.Thanksfor sharingthis!"Isaid,beforeadding"IsthereanythingIcandoforyou?" Thinkingbacktoourearlierconversation,IwantedtomakesureIheldup myendofthepartnership. "LearnC#,bemyteammate,andtogetherwe'llsavetheworld,"Noname answered. Noname'sreplyliftedmyspirits.Forasecond,allmydoubtswereoutof mindandIfeltconfidentthatallofthishardworkwouldactuallychange theworldandcreateabrighterfutureformillionsofpeople. AfterasmallpauseNonameadded,"Andplease, never setanythinginagetter.Inthegetteryougetavalue,andinthesetter yousetit.Don'tconfusethetwo. " NextAtCodeasywebelievethatlearningshouldbefunandengaging.Pleasereachouttoustoshareyourfeedbackandcollaborationideas.CompanyAboutusPricesPrivacyPolicyExtraFAQLeaderboardLanguageforbeginnersContactFollow@[email protected]



請為這篇文章評分?