get - C# Reference | Microsoft Docs

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

C# Language Specification; See also. The get keyword defines an accessor method in a property or indexer that returns the property value or ... Skiptomaincontent Thisbrowserisnolongersupported. UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport. DownloadMicrosoftEdge Moreinfo Contents Exitfocusmode ReadinEnglish Save Feedback Edit Share Twitter LinkedIn Facebook Email Tableofcontents ReadinEnglish Save Tableofcontents ReadinEnglish Save Feedback Edit Twitter LinkedIn Facebook Email Tableofcontents get(C#Reference) Article 09/15/2021 2minutestoread 10contributors Isthispagehelpful? Yes No Anyadditionalfeedback? FeedbackwillbesenttoMicrosoft:Bypressingthesubmitbutton,yourfeedbackwillbeusedtoimproveMicrosoftproductsandservices.Privacypolicy. Submit Thankyou. Inthisarticle Thegetkeyworddefinesanaccessormethodinapropertyorindexerthatreturnsthepropertyvalueortheindexerelement.Formoreinformation,seeProperties,Auto-ImplementedPropertiesandIndexers. ThefollowingexampledefinesbothagetandasetaccessorforapropertynamedSeconds.Itusesaprivatefieldnamed_secondstobackthepropertyvalue. classTimePeriod { privatedouble_seconds; publicdoubleSeconds { get{return_seconds;} set{_seconds=value;} } } Often,thegetaccessorconsistsofasinglestatementthatreturnsavalue,asitdidinthepreviousexample.StartingwithC#7.0,youcanimplementthegetaccessorasanexpression-bodiedmember.Thefollowingexampleimplementsboththegetandthesetaccessorasexpression-bodiedmembers. classTimePeriod { privatedouble_seconds; publicdoubleSeconds { get=>_seconds; set=>_seconds=value; } } Forsimplecasesinwhichaproperty'sgetandsetaccessorsperformnootheroperationthansettingorretrievingavalueinaprivatebackingfield,youcantakeadvantageoftheC#compiler'ssupportforauto-implementedproperties.ThefollowingexampleimplementsHoursasanauto-implementedproperty. classTimePeriod2 { publicdoubleHours{get;set;} } C#LanguageSpecification Formoreinformation,seetheC#LanguageSpecification.ThelanguagespecificationisthedefinitivesourceforC#syntaxandusage. Seealso C#Reference C#ProgrammingGuide C#Keywords Properties Feedback Submitandviewfeedbackfor Thisproduct Thispage Viewallpagefeedback Inthisarticle



請為這篇文章評分?