Using set to change property value in a constructor, C# - Stack ...
文章推薦指數: 80 %
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
延伸文章資訊
- 1value 內容關鍵字- C# 參考
單字 value 參考用戶端程式代碼嘗試指派給屬性或索引子的值。 在下例中, MyDerivedClass 具有稱為 Name 的屬性,它使用 value 參數將新的字串指派給支援 ...
- 2Using set to change property value in a constructor, C# - Stack ...
Your understanding of the program flow is wrong. In your constructor when you call your propertie...
- 3C# 中屬性PropertyInfo的setvalue用法說明 - 程式人生
下面是關於setvalue方法的介紹以及錯誤簡介用索引化屬性的可選索引值設定指定物件的該屬性值。
- 4C# set 與get 用法與範例| 高清水_黑白講 - - 點部落
C# set 與get 用法與範例 ... //set 存取子"設定",用於處理計算及邏輯處理. 範例一數字運算 ... 透過公用屬性set { salary = value; }
- 5C#中的屬性(get、set、value) - IT閱讀
value 關鍵字用於定義由set 取值函式分配的值。 不實現set 取值函式的屬性是隻讀的。 不實現set 取值函式的屬性是隻讀的。