Using Properties - C# Programming Guide | Microsoft Docs

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

To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set accessor. 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 UsingProperties(C#ProgrammingGuide) Article 12/09/2021 8minutestoread 14contributors Isthispagehelpful? Yes No Anyadditionalfeedback? FeedbackwillbesenttoMicrosoft:Bypressingthesubmitbutton,yourfeedbackwillbeusedtoimproveMicrosoftproductsandservices.Privacypolicy. Submit Thankyou. Inthisarticle Propertiescombineaspectsofbothfieldsandmethods.Totheuserofanobject,apropertyappearstobeafield,accessingthepropertyrequiresthesamesyntax.Totheimplementerofaclass,apropertyisoneortwocodeblocks,representingagetaccessorand/orasetaccessor.Thecodeblockforthegetaccessorisexecutedwhenthepropertyisread;thecodeblockforthesetaccessorisexecutedwhenthepropertyisassignedanewvalue.Apropertywithoutasetaccessorisconsideredread-only.Apropertywithoutagetaccessorisconsideredwrite-only.Apropertythathasbothaccessorsisread-write.InC#9andlater,youcanuseaninitaccessorinsteadofasetaccessortomakethepropertyread-only. Unlikefields,propertiesarenotclassifiedasvariables.Therefore,youcannotpassapropertyasareforoutparameter. Propertieshavemanyuses:theycanvalidatedatabeforeallowingachange;theycantransparentlyexposedataonaclasswherethatdataisactuallyretrievedfromsomeothersource,suchasadatabase;theycantakeanactionwhendataischanged,suchasraisinganevent,orchangingthevalueofotherfields. Propertiesaredeclaredintheclassblockbyspecifyingtheaccesslevelofthefield,followedbythetypeoftheproperty,followedbythenameoftheproperty,andfollowedbyacodeblockthatdeclaresaget-accessorand/orasetaccessor.Forexample: publicclassDate { privateint_month=7;//Backingstore publicintMonth { get=>_month; set { if((value>0)&&(value<13)) { _month=value; } } } } Inthisexample,MonthisdeclaredasapropertysothatthesetaccessorcanmakesurethattheMonthvalueissetbetween1and12.TheMonthpropertyusesaprivatefieldtotracktheactualvalue.Thereallocationofaproperty'sdataisoftenreferredtoastheproperty's"backingstore."Itiscommonforpropertiestouseprivatefieldsasabackingstore.Thefieldismarkedprivateinordertomakesurethatitcanonlybechangedbycallingtheproperty.Formoreinformationaboutpublicandprivateaccessrestrictions,seeAccessModifiers. Auto-implementedpropertiesprovidesimplifiedsyntaxforsimplepropertydeclarations.Formoreinformation,seeAuto-ImplementedProperties. Thegetaccessor Thebodyofthegetaccessorresemblesthatofamethod.Itmustreturnavalueofthepropertytype.Theexecutionofthegetaccessorisequivalenttoreadingthevalueofthefield.Forexample,whenyouarereturningtheprivatevariablefromthegetaccessorandoptimizationsareenabled,thecalltothegetaccessormethodisinlinedbythecompilersothereisnomethod-calloverhead.However,avirtualgetaccessormethodcannotbeinlinedbecausethecompilerdoesnotknowatcompile-timewhichmethodmayactuallybecalledatruntime.Thefollowingisagetaccessorthatreturnsthevalueofaprivatefield_name: classPerson { privatestring_name;//thenamefield publicstringName=>_name;//theNameproperty } Whenyoureferencetheproperty,exceptasthetargetofanassignment,thegetaccessorisinvokedtoreadthevalueoftheproperty.Forexample: Personperson=newPerson(); //... System.Console.Write(person.Name);//thegetaccessorisinvokedhere Thegetaccessormustendinareturnorthrowstatement,andcontrolcannotflowofftheaccessorbody. Itisabadprogrammingstyletochangethestateoftheobjectbyusingthegetaccessor.Forexample,thefollowingaccessorproducesthesideeffectofchangingthestateoftheobjecteverytimethatthe_numberfieldisaccessed. privateint_number; publicintNumber=>_number++; //Don'tdothis Thegetaccessorcanbeusedtoreturnthefieldvalueortocomputeitandreturnit.Forexample: classEmployee { privatestring_name; publicstringName=>_name!=null?_name:"NA"; } Inthepreviouscodesegment,ifyoudonotassignavaluetotheNameproperty,itwillreturnthevalueNA. Thesetaccessor Thesetaccessorresemblesamethodwhosereturntypeisvoid.Itusesanimplicitparametercalledvalue,whosetypeisthetypeoftheproperty.Inthefollowingexample,asetaccessorisaddedtotheNameproperty: classPerson { privatestring_name;//thenamefield publicstringName//theNameproperty { get=>_name; set=>_name=value; } } Whenyouassignavaluetotheproperty,thesetaccessorisinvokedbyusinganargumentthatprovidesthenewvalue.Forexample: Personperson=newPerson(); person.Name="Joe";//thesetaccessorisinvokedhere System.Console.Write(person.Name);//thegetaccessorisinvokedhere Itisanerrortousetheimplicitparametername,value,foralocalvariabledeclarationinasetaccessor. Theinitaccessor Thecodetocreateaninitaccessoristhesameasthecodetocreateasetaccessorexceptthatyouusetheinitkeywordinsteadofset.Thedifferenceisthattheinitaccessorcanonlybeusedintheconstructororbyusinganobject-initializer. Remarks Propertiescanbemarkedaspublic,private,protected,internal,protectedinternal,orprivateprotected.Theseaccessmodifiersdefinehowusersoftheclasscanaccesstheproperty.Thegetandsetaccessorsforthesamepropertymayhavedifferentaccessmodifiers.Forexample,thegetmaybepublictoallowread-onlyaccessfromoutsidethetype,andthesetmaybeprivateorprotected.Formoreinformation,seeAccessModifiers. Apropertymaybedeclaredasastaticpropertybyusingthestatickeyword.Thismakesthepropertyavailabletocallersatanytime,evenifnoinstanceoftheclassexists.Formoreinformation,seeStaticClassesandStaticClassMembers. Apropertymaybemarkedasavirtualpropertybyusingthevirtualkeyword.Thisenablesderivedclassestooverridethepropertybehaviorbyusingtheoverridekeyword.Formoreinformationabouttheseoptions,seeInheritance. Apropertyoverridingavirtualpropertycanalsobesealed,specifyingthatforderivedclassesitisnolongervirtual.Lastly,apropertycanbedeclaredabstract.Thismeansthatthereisnoimplementationintheclass,andderivedclassesmustwritetheirownimplementation.Formoreinformationabouttheseoptions,seeAbstractandSealedClassesandClassMembers. Note Itisanerrortouseavirtual,abstract,oroverridemodifieronanaccessorofastaticproperty. Examples Thisexampledemonstratesinstance,static,andread-onlyproperties.Itacceptsthenameoftheemployeefromthekeyboard,incrementsNumberOfEmployeesby1,anddisplaystheEmployeenameandnumber. publicclassEmployee { publicstaticintNumberOfEmployees; privatestaticint_counter; privatestring_name; //Aread-writeinstanceproperty: publicstringName { get=>_name; set=>_name=value; } //Aread-onlystaticproperty: publicstaticintCounter=>_counter; //AConstructor: publicEmployee()=>_counter=++NumberOfEmployees;//Calculatetheemployee'snumber: } classTestEmployee { staticvoidMain() { Employee.NumberOfEmployees=107; Employeee1=newEmployee(); e1.Name="ClaudeVige"; System.Console.WriteLine("Employeenumber:{0}",Employee.Counter); System.Console.WriteLine("Employeename:{0}",e1.Name); } } /*Output: Employeenumber:108 Employeename:ClaudeVige */ Hiddenpropertyexample Thisexampledemonstrateshowtoaccessapropertyinabaseclassthatishiddenbyanotherpropertythathasthesamenameinaderivedclass: publicclassEmployee { privatestring_name; publicstringName { get=>_name; set=>_name=value; } } publicclassManager:Employee { privatestring_name; //Noticetheuseofthenewmodifier: publicnewstringName { get=>_name; set=>_name=value+",Manager"; } } classTestHiding { staticvoidMain() { Managerm1=newManager(); //Derivedclassproperty. m1.Name="John"; //Baseclassproperty. ((Employee)m1).Name="Mary"; System.Console.WriteLine("Nameinthederivedclassis:{0}",m1.Name); System.Console.WriteLine("Nameinthebaseclassis:{0}",((Employee)m1).Name); } } /*Output: Nameinthederivedclassis:John,Manager Nameinthebaseclassis:Mary */ Thefollowingareimportantpointsinthepreviousexample: ThepropertyNameinthederivedclasshidesthepropertyNameinthebaseclass.Insuchacase,thenewmodifierisusedinthedeclarationofthepropertyinthederivedclass: publicnewstringName Thecast(Employee)isusedtoaccessthehiddenpropertyinthebaseclass: ((Employee)m1).Name="Mary"; Formoreinformationabouthidingmembers,seethenewModifier. Overridepropertyexample Inthisexample,twoclasses,CubeandSquare,implementanabstractclass,Shape,andoverrideitsabstractAreaproperty.Notetheuseoftheoverridemodifierontheproperties.Theprogramacceptsthesideasaninputandcalculatestheareasforthesquareandcube.Italsoacceptstheareaasaninputandcalculatesthecorrespondingsideforthesquareandcube. abstractclassShape { publicabstractdoubleArea { get; set; } } classSquare:Shape { publicdoubleside; //constructor publicSquare(doubles)=>side=s; publicoverridedoubleArea { get=>side*side; set=>side=System.Math.Sqrt(value); } } classCube:Shape { publicdoubleside; //constructor publicCube(doubles)=>side=s; publicoverridedoubleArea { get=>6*side*side; set=>side=System.Math.Sqrt(value/6); } } classTestShapes { staticvoidMain() { //Inputtheside: System.Console.Write("Entertheside:"); doubleside=double.Parse(System.Console.ReadLine()); //Computetheareas: Squares=newSquare(side); Cubec=newCube(side); //Displaytheresults: System.Console.WriteLine("Areaofthesquare={0:F2}",s.Area); System.Console.WriteLine("Areaofthecube={0:F2}",c.Area); System.Console.WriteLine(); //Inputthearea: System.Console.Write("Enterthearea:"); doublearea=double.Parse(System.Console.ReadLine()); //Computethesides: s.Area=area; c.Area=area; //Displaytheresults: System.Console.WriteLine("Sideofthesquare={0:F2}",s.side); System.Console.WriteLine("Sideofthecube={0:F2}",c.side); } } /*ExampleOutput: Entertheside:4 Areaofthesquare=16.00 Areaofthecube=96.00 Enterthearea:24 Sideofthesquare=4.90 Sideofthecube=2.00 */ Seealso C#ProgrammingGuide Properties InterfaceProperties Auto-ImplementedProperties Feedback Submitandviewfeedbackfor Thisproduct Thispage Viewallpagefeedback Inthisarticle



請為這篇文章評分?