getter and setter for class in class c# - Stack Overflow

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

How would I implement a correct getter and setter for the innerClass member of OuterClass? Thanks in advance! c# class member setter getter. 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 getterandsetterforclassinclassc# AskQuestion Asked 12years,10monthsago Modified 12years,10monthsago Viewed 74ktimes 17 2 AssumingwehaveaclassInnerClasswithattributesandgetter/setter.WealsohaveaclassOuterClasscontainingtheInnerClass. e.g. classInnerClass { privateintm_a; privateintm_b; publicintM_A { get { returnm_a; } set { m_a=value; } } } classOuterClass { privateInnerClassinnerClass } HowwouldIimplementacorrectgetterandsetterfortheinnerClassmemberofOuterClass? Thanksinadvance! c#classmembersettergetter Share Follow editedMay11,2009at12:42 Noldorin 138k5656goldbadges253253silverbadges298298bronzebadges askedMay11,2009at12:37 DummyCSharpDummyCSharp 2 "set"shouldbe{m_a=value;} – BinaryWorrier May11,2009at12:41 you'vegotthereptofixthatyouknow;) – annakata May11,2009at12:42 Addacomment  |  5Answers 5 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 27 Thesyntaxwouldn'tbeanydifferent.Just... publicInnerClassInnerClass { get{returninnerClass;} set{innerClass=value;} } Bytheway,ifyou'reusingC#in.NET3.5,youcanusetheautomaticpropertygenerationfeatureifallyouhaveisasimplepropertythatjustreadsandwritestoabackingstore(likeyouhaveabove).Thesytaxissimilartothatofanabstractproperty: publicInnerClassInnerClass{get;set;} Thisautomaticallygeneratesaprivatememberforstorage,thenreadsfromitinthegetandwritestoitintheset. Share Follow answeredMay11,2009at12:40 AdamRobinsonAdamRobinson 177k3131goldbadges272272silverbadges337337bronzebadges Addacomment  |  22 Themostelegantwayofdoingthisistouseimplicitgettersandsetters: classInnerClass { publicinta{get;set;} publicintb{get;set;} } classOuterClass { publicInnerClassinnerClass{get;set;} } Thisisimplicitlythesameas: classInnerClass { privateint_a; publicinta { get { return_a; } set { _a=value; } } privateint_b; publicintb { get { return_b; } set { _b=value; } } } classOuterClass { privateInnerClass_innerClass; publicInnerClassinnerClass { get { return_innerClass; } set { _innerClass=value; } } } Thesetwodefinitionsareimplicitlythesame-minusquiteafewkeystrokes.Inthefirstexample,thecompilerwillimplementthenecessaryprivatefieldsbehindthescenessoyoudon'thaveto.Thesecond,howevergivesyoumorecontrolofwhatisgoingon. Share Follow answeredMay11,2009at12:57 BenAlabasterBenAlabaster 37.5k2121goldbadges105105silverbadges148148bronzebadges 4 2 ...Howisthisdifferentfrommyanswer? – AdamRobinson May11,2009at13:11 1 Also,hegivesnoindicationoftheversionofC#/.NETthathe'susing.Implicitpropertiesareapartof.NET3.5/C#3.0only. – AdamRobinson May11,2009at13:12 2 @Adam,sorry,whenIpostedmyanswerIdidn'tseeyoursthere.IguessyoupostedasIwaswritingmyanswer. – BenAlabaster May11,2009at16:35 hi@BenAlabaster,whyjustnotdeclaringclassInnerClass{publicinta;publicintb;}Withoutgettersandsetters?Conventions?(i'mnewtocsharp) – Martin May19,2016at10:06 Addacomment  |  2 publicInnerClassInnerClass { get { returninnerClass; } set { innerClass=value; } } Share Follow answeredMay11,2009at12:40 edosoftedosoft 16.6k2424goldbadges7676silverbadges109109bronzebadges Addacomment  |  0 Itdependsonhowtheinnerclassshouldwork.Theouterclassmightneedto"own"theinnerclass,inwhichcase: publicInnerClassInnerClass{ get{returninnerClass;} set{innerClass.CopyFrom(value);/*Pseudomethodcall*/} } Bydoingitthisway,youpreventoutsidecodefrommanipulatingtheinstanceunlessexplicitlythroughOuterClass.. Share Follow answeredMay11,2009at12:45 JamesJames 64955silverbadges2222bronzebadges 2 Notreally,sinceyou'rereturningtheinstanceinthegetter.Theonlyrealwaytodothis(andthisapproachisalittlesmelly...)wouldbetousethesameCopyFrommethodtoreturnanewinstanceinthegetter. – AdamRobinson May11,2009at12:47 Ithinkyoumisunderstood.Thepointisthatyoucanmodifytheinstance,butyouhavetodoitexplicitlythroughtheinstanceofOuterClass.ExampleOuterClass.InnerClassfoo=newOuterClass.InnerClass();foo.M_A=1;outerInstance.InnerClass=foo;//outerInstance.InnerClass.M_Aequals1foo.SomeProperty=2;//outerInstance.InnerClass.M_Astillequals1outerInstance.InnerClass=foo;//outerInstance.InnerClass.M_Aequals2 – James May11,2009at19:30 Addacomment  |  0 Ifyoumeanaccessinginnerclassmemberswithoutexposingtheinnerclassitself,youcanusethefollowingcode.Ifyoujustwanttoexposethis.innerClass,thereisnodifferencetothewayyouexposethefieldsofInnerClass. classOuterClass { privateInnerClassinnerClass publicintM_A { get { if(this.innerClass!=null) { returnthis.innerClass.M_A; } else { thrownewInvalidOperationException(); } } set { if(this.innerClass!=null) { this.innerClass.M_A=value; } else { thrownewInvalidOperationException(); } } } } Share Follow answeredMay11,2009at12:46 DanielBrücknerDanielBrückner 57.4k1616goldbadges9595silverbadges141141bronzebadges 4 I'mnotsurehowthisappliesunlessImissedpartofthequestion...isthatwhathewasaskingfor? – AdamRobinson May11,2009at12:48 Justcurious-whywouldyouthrowaninvalidoperationexceptiononthegetter?Iunderstandwhyyou'ddothisinthesetter,butwouldn'tyounormallyassumethegettertobepassive? – BenAlabaster May11,2009at12:50 Ireadthequestion"[...]getterandsetterfortheinnerClassmemberofOuterClass?"withanadditional"s"as"[...]innerClassmemberSofOuterClass?",butregonizedthatonlyafterfinishingmyanswer. – DanielBrückner May11,2009at12:51 WhatwouldyoureturnifinnerClassisnull?Inarealworldscenariotheremightbeagooddefaultvalue,butIdon'tknowitfromhisquestion.Anditisnotuncommontogetanexceptionfromagetter. – DanielBrückner May11,2009at12:54 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 TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 6 Anyadvantagetoobjects.GetObject(i)overobjects[i]? Related 7159 WhatisthedifferencebetweenStringandstringinC#? 2327 ArestaticclassvariablespossibleinPython? 2771 WhatarethecorrectversionnumbersforC#? 384 PublicFieldsversusAutomaticProperties 1735 Whyusegettersandsetters/accessors? 143 Bestwayofinvokinggetterbyreflection 58 Abstractpropertywithpublicgetter,defineprivatesetterinconcreteclasspossible? 18 Whygetter&setterifreturnvalueismutable? 1694 Whatdoes"Couldnotfindorloadmainclass"mean? HotNetworkQuestions Sendingfilewithalternatedatastream? Separatingbusinesslogicfromdatatemptsmetouseinstanceof Constructiveproofofstrongnormalizationforsimplytypedlambdacalculus HowWouldHumanoidsFormTheirOwnGems? IsitappropriatetocoldcallaprospectivepostdocPI? FrameStringsthatcontainnewlines WhatwastheethniccompositionofSovietgovernment? Whywouldhydrauliccalipers(notrotors)onlybecompatiblewithresinpads? HowDoesOrbitalWarfareWork? Moviewithhuman-likesturningintoagalaxycloud(±2010orlater) Derivingtheapparentangularspeedofastar Pythontoexcel WhatisthegeographicallocationofPython(andotheropen-sourcesoftwareprojects)? Howdoeslicensingsoftwarenotimplyownership?Don'tIownaWindowsoperatingsystemonceIpayforit? Howtopolitelystatemoralobjection HowmanytimesdoIbreakmyownrule? EnigmarchDay1:Initial RecreateMinecraft'slighting Whyarerealphotonssomuchlessefficientincarryingmomentumthanvirtualphotons? NFA:Howdoesitfunctionwithempty-stringmoves? Whenandhowtoleaveafacultypositionforanewdepartment/universityorindustry ITstaffsaidthatLinuxcannotconnecttotheschool'sInternet(EduStar)andrefusedtotry Howtogetamotorcycletoaskillstest Jacobianmatrixevaluationatapoint morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?