c#: getter/setter - Stack Overflow

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

In C# 6: It is now possible to declare the auto-properties just as a field: public string FirstName { get; set; } = "Ropert";. Read-Only Auto-Properties 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 c#:getter/setter AskQuestion Asked 10years,8monthsago Modified 1year,2monthsago Viewed 293ktimes 132 20 Isawsomethinglikethefollowingsomewhere,andwaswonderingwhatitmeant.Iknowtheyaregettersandsetters,butwanttoknowwhythestringTypeisdefinedlikethis.Thanksforhelpingme. publicstringType{get;set;} c#getter-setter Share Improvethisquestion Follow askedJul15,2011at15:03 MayaMaya 6,7751111goldbadges3939silverbadges5252bronzebadges 5 weblogs.asp.net/dwahlin/archive/2007/12/04/… – Snowbear Jul15,2011at15:05 4 ThisiscalledanAuto-Property,havealookatthis:msdn.microsoft.com/en-us/library/bb384054.aspx – Allov Jul15,2011at15:05 Thisisthedefinitionofapropertynamed"Type",the.NETtypeofwhichisSystem.string.There'snothingmoretoit. – Jon Jul15,2011at15:05 2 IthinkthathemightbeconfusingthenamingoftheAuto-PropertywiththeReflectionclassSystem.Type.msdn.microsoft.com/en-us/library/system.type.aspx – eandersson Jul15,2011at15:21 stackoverflow.com/documentation/c%23/49/properties/3365/… – JonSchneider Oct4,2016at14:55 Addacomment  |  9Answers 9 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 212 ThoseareAuto-ImplementedProperties(AutoPropertiesforshort). Thecompilerwillauto-generatetheequivalentofthefollowingsimpleimplementation: privatestring_type; publicstringType { get{return_type;} set{_type=value;} } Share Improvethisanswer Follow answeredJul15,2011at15:05 JustinNiessnerJustinNiessner 235k3838goldbadges399399silverbadges529529bronzebadges 3 2 @barlopassomeonecomingfromgoogle,withnoclue,whatneedstobeupdated?IsM.Hassansanswerwhatyoumean?thanks. – Aethenosity Feb7,2019at7:17 1 @AethenosityinretrospectIthinkit'sok..Iwasthinkinigintermsofexamplesofgettersetter.Thequestionerhasavalidcaseofgettersetterthatisfarmoresuccinct(asaoneliner/nosecondfieldnecessary)..Youcanalsowritepublicintb{get{returnb*2;}}nosecondfieldnecessary.ButIthinkwhenyouhavethesetterwithabodythenyouneedthesecondfield.Andthisoneshowsasetterwithabody.Thoughitdoesthesameasthequestioner'soneliner. – barlop Feb7,2019at14:38 2 @Aethenositythereisalsoc#7wherebysureyoustillneedthesecondfieldwhenthesetterhasabody,butithasa=>syntaxandnoreturnkeyword.Thoughthatwasn'twhatIhadinmind.Ihadinmindthesecondfieldbeingunnecessary,thoughIhavesincefoundthatthesecondfieldisnecessarysometimes.Intheexampleherethesecondfieldisn'tnecessary('cosadefaultsetterwithnobodywoulddothis),buttheanswererwasputtingitin(setterbodyandsecondfield),toexplaintothequestionerwhattheirlinewithoutthesecondfieldwasdoing. – barlop Feb7,2019at14:39 Addacomment  |  39 Thatisanauto-propertyanditistheshorthandnotationforthis: privatestringtype; publicstringType { get{returnthis.type;} set{this.type=value;} } Share Improvethisanswer Follow answeredJul15,2011at15:05 TeomanSoygulTeomanSoygul 25.2k66goldbadges6868silverbadges7979bronzebadges 3 4 ...exceptthatthebackingfieldisnotaccessible. – Vlad Jul15,2011at15:09 9 ...whichiswhyitiscalledthebackingfield. – TeomanSoygul Jul15,2011at15:11 5 Nevertheless,youshouldbeableseeitask__BackingFieldwithreflection. – Vlad Jul15,2011at15:38 Addacomment  |  31 InC#6: Itisnowpossibletodeclaretheauto-propertiesjustasafield: publicstringFirstName{get;set;}="Ropert"; Read-OnlyAuto-Properties publicstringFirstName{get;}="Ropert"; Share Improvethisanswer Follow answeredJul18,2016at22:48 M.HassanM.Hassan 9,06855goldbadges5656silverbadges7979bronzebadges Addacomment  |  16 publicstringType{get;set;} isnodifferentthandoing privatestring_Type; publicstringType { get{return_Type;} set{_Type=value;} } Share Improvethisanswer Follow editedJan6,2021at0:47 Pang 8,994145145goldbadges8282silverbadges117117bronzebadges answeredJul15,2011at15:10 SecurityHoundSecurityHound 2,51233goldbadges2424silverbadges4141bronzebadges 0 Addacomment  |  8 Thismeansthatthecompilerdefinesabackingfieldatruntime.Thisisthesyntaxforauto-implementedproperties. MoreInformation:Auto-ImplementedProperties Share Improvethisanswer Follow editedJan6,2021at0:46 Pang 8,994145145goldbadges8282silverbadges117117bronzebadges answeredJul15,2011at15:05 MaverikMaverik 5,5293535silverbadges4646bronzebadges Addacomment  |  5 It'sanautomaticallybackedproperty,basicallyequivalentto: privatestringtype; publicstringType { get{returntype;} set{type=value;} } Share Improvethisanswer Follow editedJan6,2021at0:45 Pang 8,994145145goldbadges8282silverbadges117117bronzebadges answeredJul15,2011at15:06 JamiecJamiec 128k1212goldbadges131131silverbadges185185bronzebadges Addacomment  |  4 Thesearecalledautoproperties. http://msdn.microsoft.com/en-us/library/bb384054.aspx Functionally(andintermsofthecompiledIL),theyarethesameaspropertieswithbackingfields. Share Improvethisanswer Follow answeredJul15,2011at15:05 JeffJeff 34.3k1414goldbadges100100silverbadges207207bronzebadges 4 1 Canyoustillreferencetheprivate_typeortypewithintheclass,oryoujustuseType? – mikey Jul15,2011at15:07 2 No,BUTyoucanspecifythemodifierfortheautoproperty:publicstringType{get;privateset;} – Jeff Jul15,2011at15:09 Youwouldbeunabletoaccess_typeinthiscase. – SecurityHound Jul15,2011at15:10 1 Sointhatcasethis.Type="foo";shouldbeOK,butfromoutsideinstance.Type="foo";willnot..Theseautopropsaredefinitelyahelpfuladditiontothelanguage.Thanks. – mikey Jul15,2011at15:12 Addacomment  |  3 Youcanalsousealambdaexpression publicstringType { get=>_type; set=>_type=value; } Share Improvethisanswer Follow editedApr2,2020at3:23 Frederic 1,97022goldbadges1818silverbadges3232bronzebadges answeredDec15,2019at15:07 AhmadAghazadehAhmadAghazadeh 15.7k1111goldbadges9595silverbadges9393bronzebadges Addacomment  |  1 WiththereleaseofC#6,youcannowdosomethinglikethisforprivateproperties. publicconstructor() { myProp="somevalue"; } publicstringmyProp{get;} Share Improvethisanswer Follow editedJan6,2021at0:49 Pang 8,994145145goldbadges8282silverbadges117117bronzebadges answeredOct2,2015at11:25 AnonymousAnonymous 1,93722goldbadges2727silverbadges3434bronzebadges 1 3 youcansetinitialvaluedirectlyinC#6:publicstringmyProp{get;}="somevalue")withoutconstructor; – M.Hassan Jul19,2016at8:39 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#getter-setteroraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 0 InterceptasetterinC# 1 Whatisthepurposeofget:set? 1 publicClassname[][]Methodname{get;set;}whatdoesthismeaninc#? 2 CS0122Form1.AvgWaitingisinaccessibleduetoitsprotectionlevelandganttchartinC#WindowsForm 0 AdditionalMethodsthatdonotwork? 1 DefaultsetterparaminC# 0 passingvariablesformtoformprivatetoglobalinc#? Related 945 StringrepresentationofanEnum 3229 Caseinsensitive'Contains(string)' 982 Howwouldyoucountoccurrencesofastring(actuallyachar)withinastring? 520 AssociatingenumswithstringsinC# 540 GettingattributesofEnum'svalue 1876 HowdoIremedy"Thebreakpointwillnotcurrentlybehit.Nosymbolshavebeenloadedforthisdocument."warning? 1791 IsthereareasonforC#'sreuseofthevariableinaforeach? 1597 WhynotinheritfromList? HotNetworkQuestions WhatwouldUkrainegainbydisclosingintelligenceinformationaboutPutinassassinationplans? WhydoesAgustínsay"miércoles"intheEncantomovie?Whatdoesitmean? Howtopolitelystatemoralobjection Derivingtheapparentangularspeedofastar Haskellcomparingtwolists'lengthsbutoneofthemisinfinite? Simplequadraticfunction,butcan'tunderstandthequestion WheredidthethirdsyllableoftheletterWinWD-40go? HowtobreakstringintoN80characterlines? Woulditbepossibleforoneairlinertotowanother? My(manual)transmissionwon'tengageanygear1dayafterescapingbog WhydoesahypersonicmissileneedtocruiseEarthatlowaltitudebeforehittingitsmark? CanIsubmitmytaxesinmultipleenvelopes? Whatisagoodsoftwaretomaketechincaland/orschematicillustrationsaboutspace/orbitaldynamicstopics? Fallout4chemistryworkstation-backgroundimageusedforreflections WhatcanweeatinthelateCretaceous? HowdoyouexplainCanada'sTrudeau'spower-sharingagreementtoafive-year-old(American)? Howtoselectallcurvesonoroutsidearegion? Depassivavocecumverbisquaecasumdativumpostulant Isthereaconventionfordocumentingaschematicwithnotes? Moviewithhuman-likesturningintoagalaxycloud(±2010orlater) GettingonepointwithcoordinatesforpolygoninQGIS Sandboxoverflow HowmanytimesdoIbreakmyownrule? Iturnedabreakeroff,andnowthesecurityalarmsystemwon’tstopbeeping morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?