Looking for a short & simple example of getters/setters in C# ...
文章推薦指數: 80 %
I think a bit of code will help illustrate what setters and getters are: public class Foo { private string bar; public string GetBar() ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Lookingforashort&simpleexampleofgetters/settersinC# AskQuestion Asked 9years,9monthsago Modified 3monthsago Viewed 146ktimes 61 26 IamhavingtroubleunderstandingtheconceptofgettersandsettersintheC#language.InlanguageslikeObjective-C,theyseemanintegralpartofthesystem,butnotsomuchinC#(asfarasIcantell).Ihavereadbooksandarticlesalready,somyquestionis,tothoseofyouwhounderstandgetters&settersinC#,whatexamplewouldyoupersonallyuseifyouwereteachingtheconcepttoacompletebeginner(thiswouldincludeasfewlinesofcodeaspossible)? c#settergettergetter-setter Share Follow editedJun22,2012at15:43 SliverNinja-MSFT 29.9k1111goldbadges100100silverbadges166166bronzebadges askedJun22,2012at15:35 CM90CM90 72511goldbadge66silverbadges99bronzebadges 7 Thisisprettybroad.WhatspecificallyisgivingyoutroublewithC#properties? – arcain Jun22,2012at15:39 Thisisprobablyaduplicateofstackoverflow.com/questions/1209359/properties-and-methods – arcain Jun22,2012at15:41 Iwonderwhatismissingatgetters/settersinC#incomparisontoObjectiveC? – Vlad Jun22,2012at15:41 2 Everybodylearnsdifferently,andinthiscasebroadnessmaybeanadvantagebecauseifeachexperiencedcodergivesanexampleinthewaythatmakessensetothem,thenhopefullyatleastoneanswerwillmakesensetoeachreader.Iwillcheckoutthispossibleduplicateinasecond.IknowverylittleObj-CotherthanwhatIwasabletoteachmyself,butitseemedlikeyouhadtogetandseteverything,whereasinC#I'veneverhadtodoso... – CM90 Jun22,2012at15:53 @CM90:actually,youcanhavetheusualvariables(withoutgetters/setters)inObjectiveC,especiallyinthepartsnotinteractingwithCocoa. – Vlad Jun22,2012at16:06 | Show2morecomments 12Answers 12 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 83 Ithinkabitofcodewillhelpillustratewhatsettersandgettersare: publicclassFoo { privatestringbar; publicstringGetBar() { returnbar; } publicvoidSetBar(stringvalue) { bar=value; } } Inthisexamplewehaveaprivatememberoftheclassthatiscalledbar.TheGetBarandSetBarmethodsdoexactlywhattheyarenamed-oneretrievesthebarmember,andtheothersetsitsvalue. Inc#1.1+youhaveproperties.Thebasicfunctionalityisalsothesame: publicclassFoo { privatestringbar; publicstringBar { get{returnbar;} set{bar=value;} } } Theprivatememberbarisnotaccessibleoutsidetheclass.Howeverthepublic"Bar"is,andithastwoaccessors-get,whichjustastheexampleabove"GetBar()"returnstheprivatemember,andalsoaset-whichcorrespondstotheSetBar(stringvalue)methodintheforementionedexample. StartingwithC#3.0andabovethecompilerbecameoptimizedtothepointwheresuchpropertiesdonotneedtohavetheprivatememberastheirsource.Thecompilerautomaticallygeneratesaprivatememberofthattypeandusesitasasourceofaproperty. publicclassFoo { publicstringBar{get;set;} } whatthecodeshowsisanautomaticpropertythathasaprivatemembergeneratedbythecompiler.Youdon'tseetheprivatememberbutitisthere.Thisalsointroducedacoupleofotherissues-mainlywithaccesscontrol.InC#1.1,and2.0youcouldomitthegetorsetportionofaproperty: publicclassFoo { privatestringbar; publicstringBar { get{returnbar;} } } Givingyouthechancetorestricthowotherobjectsinteractwiththe"Bar"propertyoftheFooclass.StartingwithC#3.0andabove-ifyouchosetouseautomaticpropertiesyouwouldhavetospecifytheaccesstothepropertyasfollows: publicclassFoo { publicstringBar{get;privateset;} } WhatthatmeansisthatonlytheclassitselfcansetBartosomevalue,howeveranyonecouldreadthevalueinBar. Share Follow editedJan3,2014at17:34 Felix 3,19355goldbadges3131silverbadges4747bronzebadges answeredJun22,2012at15:49 bleepzterbleepzter 8,8911111goldbadges3939silverbadges6363bronzebadges Addacomment | 30 InC#,PropertiesrepresentyourGettersandSetters. Here'sanexample: publicclassPropertyExample { privateintmyIntField=0; publicintMyInt { //Thisisyourgetter. //itusestheaccessibilityoftheproperty(public) get { returnmyIntField; } //thisisyoursetter //Note:youcanspecifydifferentaccessibility //foryourgetterandsetter. protectedset { //Youcanputlogicintoyourgettersandsetters //sincetheyactuallymaptofunctionsbehindthescenes if(DoSomeValidation(value)) { //Theinputofthesetterisalwayscalled"value" //andisofthesametypeasyourpropertydefinition myIntField=value; } } } } Youwouldaccessthispropertyjustlikeafield.Forexample: PropertyExampleexample=newPropertyExample(); example.MyInt=4;//setsmyIntFieldto4 Console.WriteLine(example.MyInt);//prints4 Afewotherthingstonote: Youdon'thavetospecifiybothagetterandasetter,youcanomiteitherone. Propertiesarejust"syntacticsugar"foryourtraditionalgetterandsetter.Thecompilerwillactuallybuildget_andset_functionsbehindthescenes(inthecompiledIL)andmapallreferencestoyourpropertytothosefunctions. Share Follow editedMar25,2021at16:04 HansKesting 35.9k88goldbadges7777silverbadges104104bronzebadges answeredJun22,2012at15:39 JonSenchynaJonSenchyna 7,57922goldbadges2424silverbadges4545bronzebadges Addacomment | 14 Mostlanguagesdoitthisway,andyoucandoitinC#too. publicvoidsetRAM(intRAM) { this.RAM=RAM; } publicintgetRAM() { returnthis.RAM; } ButC#alsogivesamoreelegantsolutiontothis: publicclassComputer { intram; publicintRAM { get { returnram; } set { ram=value;//valueisareservedwordanditisavariablethatholdstheinputthatisgiventoram(likeintheexamplebelow) } } } Andlateraccessitwith: Computercomp=newComputer(); comp.RAM=1024; intvar=comp.RAM; FornewerversionsofC#it'sevenbetter: publicclassComputer { publicintRAM{get;set;} } andlater: Computercomp=newComputer(); comp.RAM=1024; intvar=comp.RAM; Share Follow editedDec10,2021at2:22 JoshCorreia 2,66011goldbadge2424silverbadges3737bronzebadges answeredJun22,2012at15:40 IkspetoIkspeto 58266silverbadges1212bronzebadges 1 2 Thanksforexplainingwhatvalueactuallyis – jskidd3 Nov11,2017at18:07 Addacomment | 13 Myexplanationwouldbefollowing.(It'snotsoshort,butit'squitesimple.) Imagineaclasswithavariable: classSomething { intweight; //andothermethods,ofcourse,notshownhere } Well,thereisasmallproblemwiththisclass:noonecanseetheweight.Wecouldmakeweightpublic,buttheneveryonewouldbeabletochangetheweightatanymoment(whichisperhapsnotwhatwewant).So,well,wecandoafunction: classSomething { intweight; publicintGetWeight(){returnweight;} //andothermethods } Thisisalreadybetter,butnoweveryoneinsteadofplainsomething.Weighthastotypesomething.GetWeight(),whichis,well,ugly. Withproperties,wecandothesame,butthecodestaysclean: classSomething { publicintweight{get;privateset;} //andothermethods } intw=something.weight//works! something.weight=x;//doesn'tevencompile Nice,sowiththepropertieswehavefinercontroloverthevariableaccess. Anotherproblem:okay,wewanttheoutercodetobeabletosetweight,butwe'dliketocontrolitsvalue,andnotallowtheweightslowerthan100.Moreover,thereareissomeotherinnervariabledensity,whichdependsonweight,sowe'dwanttorecalculatethedensityassoonastheweightchanges. Thisistraditionallyachievedinthefollowingway: classSomething { intweight; publicintSetWeight(intw) { if(w<100) thrownewArgumentException("weighttoosmall"); weight=w; RecalculateDensity(); } //andothermethods } something.SetWeight(anotherSomething.GetWeight()+1); Butagain,wedon'twantexposetoourclientsthatsettingtheweightisacomplicatedoperation,it'ssemanticallynothingbutassigninganewweight.Sothecodewithasetterlooksthesameway,butnicer: classSomething { privateint_w; publicintWeight { get{return_w;} set { if(value<100) thrownewArgumentException("weighttoosmall"); _w=value; RecalculateDensity(); } } //andothermethods } something.Weight=otherSomething.Weight+1;//muchcleaner,right? So,nodoubt,propertiesare"just"asyntacticsugar.Butitmakestheclient'scodebebetter.Interestingly,theneedforproperty-likethingsarisesveryoften,youcancheckhowoftenyoufindthefunctionslikeGetXXX()andSetXXX()intheotherlanguages. Share Follow editedDec30,2018at7:21 KeremBaydoğan 10.1k11goldbadge3838silverbadges4949bronzebadges answeredJun22,2012at15:57 VladVlad 34.2k66goldbadges7777silverbadges192192bronzebadges 2 ReallyNiceExplanation:) – CrazyProgrammer Feb12,2014at10:14 ThisisthebestexplanationforthisquestionIMO,BTWIhavechangedgreater-thansigntoless-thansignbecausethebugannoyedmegreatlywhilereadingtheexplanation. – KeremBaydoğan Dec30,2018at7:20 Addacomment | 6 C#introducespropertieswhichdomostoftheheavyliftingforyou... ie publicstringName{get;set;} isaC#shortcuttowriting... privatestring_name; publicstringgetName{return_name;} publicvoidsetName(stringvalue){_name=value;} Basicallygettersandsettersarejustmeansofhelpingencapsulation.Whenyoumakeaclassyouhaveseveralclassvariablesthatperhapsyouwanttoexposetootherclassestoallowthemtogetaglimpseofsomeofthedatayoustore.Whilejustmakingthevariablespublictobeginwithmayseemlikeanacceptablealternative,inthelongrunyouwillregretlettingotherclassesmanipulateyourclassesmembervariablesdirectly.Ifyouforcethemtodoitthroughasetter,youcanaddlogictoensurenostrangevalueseveroccur,andyoucanalwayschangethatlogicinthefuturewithouteffectingthingsalreadymanipulatingthisclass. ie privatestring_name; publicstringgetName{return_name;} publicvoidsetName(stringvalue) { //Don'twantthingssettingmyNametonull if(value==null) { thrownewInvalidInputException(); } _name=value; } Share Follow editedOct20,2017at18:57 leewz 2,97111goldbadge1515silverbadges3636bronzebadges answeredJun22,2012at15:44 KevinDiTragliaKevinDiTraglia 24.8k1919goldbadges9090silverbadges135135bronzebadges 2 silentignoringthesetterinthecaseofbadinputisusuallyabadidea – Vlad Jun22,2012at16:03 Probablyokforasimpleexample,butIeditedinanexceptionratherthanasilentignore. – KevinDiTraglia Jun22,2012at16:07 Addacomment | 3 wellhereiscommonusageofgettersetterinactualusecase, publicclassOrderItem { publicintId{get;set;} publicintquantity{get;set;} publicintPrice{get;set;} publicintTotalAmount{get{returnthis.quantity*this.Price;}set;} } Share Follow editedMay31,2018at19:06 CommunityBot 111silverbadge answeredFeb16,2015at9:19 ArashArash 3,02955goldbadges2828silverbadges4444bronzebadges Addacomment | 1 Thiswouldbeaget/setinC#usingthesmallestamountofcodepossible.Yougetauto-implementedpropertiesinC#3.0+. publicclassContact { publicstringName{get;set;} } Share Follow answeredJun22,2012at15:41 SliverNinja-MSFTSliverNinja-MSFT 29.9k1111goldbadges100100silverbadges166166bronzebadges Addacomment | 1 AsfarasIunderstandgettersandsettersaretoimproveencapsulation. ThereisnothingcomplexabouttheminC#. Youdefineapropertyofonobjectlikethis: intm_colorValue=0; publicintColor { set{m_colorValue=value;} get{returnm_colorValue;} } Thisisthemostsimpleuse.Itbasicallysetsaninternalvariableorretrievesitsvalue. YouuseaPropertylikethis: someObject.Color=222;//setsacolor222 intcolor=someObject.Color//getsthecoloroftheobject Youcouldeventuallydosomeprocessingonthevalueinthesettersorgetterslikethis: publicintColor { set{m_colorValue=value+5;} get{returnm_colorValue-30;} } ifyouskipsetorget,yourpropertywillbereadorwriteonly.That'showIunderstandthestuff. Share Follow editedJun22,2012at17:28 ThiemNguyen 6,28777goldbadges2828silverbadges5050bronzebadges answeredJun22,2012at15:44 ZingamZingam 4,21066goldbadges2525silverbadges4343bronzebadges Addacomment | 1 Simpleexample publicclassSimple { publicintPropery{get;set;} } Share Follow editedJul29,2012at20:15 burning_LEGION 12.8k88goldbadges3838silverbadges5050bronzebadges answeredJun22,2012at15:42 KF2KF2 9,37188goldbadges3838silverbadges7676bronzebadges Addacomment | 0 GettersandSettersinC#aresomethingthatsimplifiesthecode. privatestringname="spots"; publicstringName { get{returnname;} set{name=value;} } Andcallingit(assumewehaveapersonobjwithanameproperty): Console.WriteLine(Person.Name);//prints"spots" Person.Name="stops"; Console.Writeline(Person.Name);//prints"stops" Thissimplifiesyourcode.WhereinJavayoumighthavetohavetwomethods,onetoGet()andonetoSet()theproperty,inC#itisalldoneinonespot.Iusuallydothisatthestartofmyclasses: publicstringfoobar{get;set;} Thiscreatesagetterandsetterformyfoobarproperty.Callingitisthesamewayasshownbefore.Somethingstonotearethatyoudon'thavetoincludebothgetandset.Ifyoudon'twantthepropertybeingmodified,don'tincludeset! Share Follow answeredJun22,2012at15:49 spotsspots 2,01244goldbadges2323silverbadges3535bronzebadges Addacomment | 0 Internally,gettersandsettersarejustmethods.WhenC#compiles,itgeneratesmethodsforyourgettersandsetterslikethis,forexample: publicintget_MyProperty(){...} publicvoidset_MyProperty(intvalue){...} C#allowsyoutodeclarethesemethodsusingashort-handsyntax.Thelinebelowwillbecompiledintothemethodsabovewhenyoubuildyourapplication. publicintMyProperty{get;set;} or privateintmyProperty; publicintMyProperty { get{returnmyProperty;} set{myProperty=value;}//valueisanimplicitparametercontainingthevaluebeingassignedtotheproperty. } Share Follow editedJun22,2012at15:51 answeredJun22,2012at15:45 KevinAenmeyKevinAenmey 12.9k55goldbadges4343silverbadges4444bronzebadges Addacomment | 0 Thisisabasicexampleofanobject"Article"withgettersandsetters: publicclassArticle { publicStringtitle; publicStringlink; publicStringdescription; publicstringgetTitle() { returntitle; } publicvoidsetTitle(stringvalue) { title=value; } publicstringgetLink() { returnlink; } publicvoidsetLink(stringvalue) { link=value; } publicstringgetDescription() { returndescription; } publicvoidsetDescription(stringvalue) { description=value; } } Share Follow answeredMar17,2015at18:45 JorgesysJorgesys 119k2323goldbadges312312silverbadges255255bronzebadges 1 1 Thelessernicethinghereisthatthevariablesthemselvesaremadepublic,whichisabadOOparadigm.Especiallywhenyouhaveexplicitsettersandgettersnexttoit.MuchbetteristodeploytheC#paradigm:publicStringTitle{get;set};(samefortheother2variables).Thisincapsulatesthe(notvisible,butgenerated)privatevariablefromtheoutsideworld. – GeertVc Sep17,2016at17:37 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc#settergettergetter-setteroraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 27 HowdoIcallagetterorsetterinC# 12 WhentousePropertiesandMethods? 1 C#Howtousemethodsfromoneclassinanotherclass 0 isitpossibletoaddifconditionwhenaddingvaluestoaclass 0 Angular-DynamicallysettingHTMLattributewith'setAttribute' Related 247 HowcanwegenerategettersandsettersinVisualStudio? 198 InC#,Whatisamonad? 141 Getters\settersfordummies 1735 Whyusegettersandsetters/accessors? 112 Howdogettersandsetterswork? 522 What'sthepythonicwaytousegettersandsetters? 775 Using@propertyversusgettersandsetters 2 Canunderstandsettersandgettersinjava 208 Propertygettersandsetters HotNetworkQuestions Couldvideosbeauthenticatedusingprivateandpublickeys? Woulditbepossibleforoneairlinertotowanother? WordpressRedirect301registerpage Haskellcomparingtwolists'lengthsbutoneofthemisinfinite? HowdoyouexplainCanada'sTrudeau'spower-sharingagreementtoafive-year-old(American)? HowDoesOrbitalWarfareWork? ConnectingHundredsofServersviaLocalNetwork(LAN)? HowcanIpreservebooks,butkeepthemaccessible? WhatwastheethniccompositionofSovietgovernment? Howtomotivatestafftoattendapaidcertification? IsthisUrsineplayerracebalanced? Whyarerealphotonssomuchlessefficientincarryingmomentumthanvirtualphotons? Separatingbusinesslogicfromdatatemptsmetouseinstanceof EnigmarchDay1:Initial Whydoesn'ttheUSsendairplanestoUkraine,whenRussianssentMIGstoVietnamduringVietnamwar? Plantingmulberrytoodeep Willunevenspeedberoundedupordown? Howtogetamotorcycletoaskillstest Howdoeslicensingsoftwarenotimplyownership?Don'tIownaWindowsoperatingsystemonceIpayforit? Whatisagoodsoftwaretomaketechincaland/orschematicillustrationsaboutspace/orbitaldynamicstopics? Whywouldhydrauliccalipers(notrotors)onlybecompatiblewithresinpads? Reasonssomeonewouldavoidworkingoncareergrowth Typingabashcommand,I'matitsthirdline.ButhowdoIreturntoitsbeginningtoeditsomethingI'vemissed? Spaceshipshooter morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1get - C# Reference | Microsoft Docs
C# Language Specification; See also. The get keyword defines an accessor method in a property or ...
- 2C# 7.0 Expression Bodied Members
Lambda expressions can be written in short form without curly brackets when the statement consist...
- 3C# short getter setter Code Example - Code Grepper
Whatever answers related to “C# short getter setter”. what is static setter and getter examples i...
- 4Looking for a short & simple example of getters/setters in C# ...
I think a bit of code will help illustrate what setters and getters are: public class Foo { priva...
- 5Getters setters and auto properties in C# explained { get; set
I have had a few questions from people asking me to elaborate on the concept of Getters and Sette...