Using set to change property value in a constructor, C# - Stack ...

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

Your understanding of the program flow is wrong. In your constructor when you call your properties to set value, the program flow will run ... 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 Usingsettochangepropertyvalueinaconstructor,C# AskQuestion Asked 5monthsago Modified 5monthsago Viewed 162times 0 TheprogramIwroteworks,andprintsfine.Itcreatestwoobjectsfine.Oneobjectistobecreatedusingtheno-argdefaultconstructor,andtheotheristobecreatedfromthenon-defaultconstructor.TheonlydifferenceisIamsupposedtousethesetkeywordforAuthortocreateadefaultvalue.SothatwhenIgotocreatetheobjectwiththewrongauthornameitwillchangeitusingthesetkeyword. WhenIenterinthewrongvalueforBook1.Authorforthenon-defaultconstructor,itchangesbothAuthornamesinbothobjects.HowdoIonlyallowittochangetheauthornameinmyBook1object? usingSystem; namespaceBook { publicclassBook { privatestring_Author; privatestring_Title; privatestring_Keywords; privatestring_publicationDate; privatestring_ISBN; publicBook() { Author=""; } publicBook(stringtitle,stringauthor,stringpublicationDate,stringkeywords,stringisbn) { Title=title; Author=author; Keywords=keywords; PublicationDate=publicationDate; ISBN=isbn; } publicstringTitle{get=>_Title;set=>_Title=value;} publicstringAuthor{get=>_Author;set=>_Author="MaryDelamaterandJoelMurach,";} publicstringKeywords{get=>_Keywords;set=>_Keywords=value;} publicstringPublicationDate{get=>_publicationDate;set=>_publicationDate=value;} publicstringISBN{get=>_ISBN;set=>_ISBN=value;} publicoverridestringToString() { returnTitle+Author+PublicationDate+"Keywords:"+Keywords+"ISBN"+ISBN; } } } usingSystem; namespaceBook { classProgram { staticvoidMain(string[]args) { BookBook1=newBook("murach'sASP.NETCoreMVC,","MaryDelamaterandJoelMurach,","January2020,","C#,Programming,MVC,ASP.NET,Core,Beginner","978-1-943872-49-7"); Console.WriteLine(Book1.ToString()); BookBook2=newBook(); Book2.Title="C#InDepth,"; Book2.Author="JohnSkeet,"; Book2.PublicationDate="March23,2019,"; Book2.Keywords="C#,InDepth"; Book2.ISBN="9781617294532"; Console.WriteLine(Book2.ToString()); } } } c#constructorobject-create Share Follow askedOct24,2021at1:56 Kcampbell22Kcampbell22 1522bronzebadges 3 Canyoupostthesamplewhatcanbegoingwrong? – Serge Oct24,2021at2:05 "WhenIenterinthewrongvalueforBook1.Author....itchangesbothAuthornamesinbothobjects."whatobjectsareyoutalkingabout? – Serge Oct24,2021at2:06 1 set=>_Author="MaryDelamaterandJoelMurach,";shouldbeset=>_Author=value;,surely?Andyou'dassigntheintendedstringfromthespecificplace?Thesetterisn'tthedefault;itiswhathappensanytimeyouassignanyvaluetotheproperty,andrightnow,whathappensisyouignorethevaluebeingassigned,andchangethefieldtoafixedvalue – MarcGravell Oct24,2021at6:59 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 0 Yourunderstandingoftheprogramflowiswrong.Inyourconstructorwhenyoucallyourpropertiestosetvalue,theprogramflowwillrunthesetpartwhichyouhardcodedtoastring.Nowifyoutrytosaveyourvalueviathispropertybyanobjectorinaconstructoritwillalwayssettothehardcodedvalueirrespectiveofwhatyouwant.Tostoreacustomvalue,youhavetouseset=>valueandtoapplyyourbusinessconstraint,youcanwritelogicalconditionsinsideyourpropertywhichiswhypropertiesareusedfortoachieveencapsulation. Somethinglikethis: publicstringAuthor{ get{ return_Author; } set{ if()//yourconditiontovalidateifauthoriswrong _Author="";//yourexpectedcorrectauthorname else _Author=value } } Share Follow answeredOct24,2021at7:30 dark_cypherdark_cypher 5877bronzebadges 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#constructorobject-createoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Related 1731 CallingthebaseconstructorinC# 2184 WhatisthebestwaytogiveaC#auto-propertyaninitialvalue? 1407 Virtualmembercallinaconstructor 2286 Should'using'directivesbeinsideoroutsidethenamespace? 2518 HowdoIcalloneconstructorfromanotherinJava? 1056 CanIcallaconstructorfromanotherconstructor(doconstructorchaining)inC++? 2149 GetintvaluefromenuminC# 1085 Getpropertyvaluefromstringusingreflection 1190 Calloneconstructorfromanother 0 Javascript:Defaultprototypefieldsshowingundefinedforobjectcreatedusingnullconstructor HotNetworkQuestions Retainingambitiousemployeewithrareskillset WordpressRedirect301registerpage HowcanIreplaceastringinatext? IfIdisagreewiththeresearchcommunity,shouldIreviewpapersaccordingtomybeliefsorthecommunity's? Howtopolitelystatemoralobjection Pythontoexcel HasRowlingeverrecognisedmistakesorinconsistencies? HowcanIrotatea2Dshapewithrespecttoanother? HowchangeinKEissameineveryinertialreferenceframe? TikZarcwithextremeangle Howtogetamotorcycletoaskillstest FrameStringsthatcontainnewlines FitdatawithNormalDistribution Plantingmulberrytoodeep Derivingtheapparentangularspeedofastar Typingabashcommand,I'matitsthirdline.ButhowdoIreturntoitsbeginningtoeditsomethingI'vemissed? ArrangeaHaft-Sintable IfplayerAisincheckbuthasamovewhichwillcheckmateplayerBwithoutexitingcheck,isthatmovelegal? StopPipesFromPullingThroughTheWall EnigmarchDay1:Initial Howdoestheprincipleofrelativityimplythatphotonclocksandmechanicalclocksexperiencetimedilationthesameway? WhatwouldUkrainegainbydisclosingintelligenceinformationaboutPutinassassinationplans? Simplequadraticfunction,butcan'tunderstandthequestion WhatisthegeographicallocationofPython(andotheropen-sourcesoftwareprojects)? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?