C# - Properties - Tutorialspoint

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

C# - Properties ... Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. C#BasicTutorial C#-Home C#-Overview C#-Environment C#-ProgramStructure C#-BasicSyntax C#-DataTypes C#-TypeConversion C#-Variables C#-Constants C#-Operators C#-DecisionMaking C#-Loops C#-Encapsulation C#-Methods C#-Nullables C#-Arrays C#-Strings C#-Structure C#-Enums C#-Classes C#-Inheritance C#-Polymorphism C#-OperatorOverloading C#-Interfaces C#-Namespaces C#-PreprocessorDirectives C#-RegularExpressions C#-ExceptionHandling C#-FileI/O C#AdvancedTutorial C#-Attributes C#-Reflection C#-Properties C#-Indexers C#-Delegates C#-Events C#-Collections C#-Generics C#-AnonymousMethods C#-UnsafeCodes C#-Multithreading C#UsefulResources C#-QuestionsandAnswers C#-QuickGuide C#-UsefulResources C#-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho C#-Properties Advertisements PreviousPage NextPage  Propertiesarenamedmembersofclasses,structures,andinterfaces.MembervariablesormethodsinaclassorstructuresarecalledFields.Propertiesareanextensionoffieldsandareaccessedusingthesamesyntax.Theyuseaccessorsthroughwhichthevaluesoftheprivatefieldscanberead,writtenormanipulated. Propertiesdonotnamethestoragelocations.Instead,theyhaveaccessorsthatread,write,orcomputetheirvalues. Forexample,letushaveaclassnamedStudent,withprivatefieldsforage,name,andcode.Wecannotdirectlyaccessthesefieldsfromoutsidetheclassscope,butwecanhavepropertiesforaccessingtheseprivatefields. Accessors Theaccessorofapropertycontainstheexecutablestatementsthathelpsingetting(readingorcomputing)orsetting(writing)theproperty.Theaccessordeclarationscancontainagetaccessor,asetaccessor,orboth.Forexample− //DeclareaCodepropertyoftypestring: publicstringCode{ get{ returncode; } set{ code=value; } } //DeclareaNamepropertyoftypestring: publicstringName{ get{ returnname; } set{ name=value; } } //DeclareaAgepropertyoftypeint: publicintAge{ get{ returnage; } set{ age=value; } } Example Thefollowingexampledemonstratesuseofproperties− LiveDemo usingSystem; namespacetutorialspoint{ classStudent{ privatestringcode="N.A"; privatestringname="notknown"; privateintage=0; //DeclareaCodepropertyoftypestring: publicstringCode{ get{ returncode; } set{ code=value; } } //DeclareaNamepropertyoftypestring: publicstringName{ get{ returnname; } set{ name=value; } } //DeclareaAgepropertyoftypeint: publicintAge{ get{ returnage; } set{ age=value; } } publicoverridestringToString(){ return"Code="+Code+",Name="+Name+",Age="+Age; } } classExampleDemo{ publicstaticvoidMain(){ //CreateanewStudentobject: Students=newStudent(); //Settingcode,nameandtheageofthestudent s.Code="001"; s.Name="Zara"; s.Age=9; Console.WriteLine("StudentInfo:{0}",s); //letusincreaseage s.Age+=1; Console.WriteLine("StudentInfo:{0}",s); Console.ReadKey(); } } } Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult− StudentInfo:Code=001,Name=Zara,Age=9 StudentInfo:Code=001,Name=Zara,Age=10 AbstractProperties Anabstractclassmayhaveanabstractproperty,whichshouldbeimplementedinthederivedclass.Thefollowingprogramillustratesthis− LiveDemo usingSystem; namespacetutorialspoint{ publicabstractclassPerson{ publicabstractstringName{ get; set; } publicabstractintAge{ get; set; } } classStudent:Person{ privatestringcode="N.A"; privatestringname="N.A"; privateintage=0; //DeclareaCodepropertyoftypestring: publicstringCode{ get{ returncode; } set{ code=value; } } //DeclareaNamepropertyoftypestring: publicoverridestringName{ get{ returnname; } set{ name=value; } } //DeclareaAgepropertyoftypeint: publicoverrideintAge{ get{ returnage; } set{ age=value; } } publicoverridestringToString(){ return"Code="+Code+",Name="+Name+",Age="+Age; } } classExampleDemo{ publicstaticvoidMain(){ //CreateanewStudentobject: Students=newStudent(); //Settingcode,nameandtheageofthestudent s.Code="001"; s.Name="Zara"; s.Age=9; Console.WriteLine("StudentInfo:-{0}",s); //letusincreaseage s.Age+=1; Console.WriteLine("StudentInfo:-{0}",s); Console.ReadKey(); } } } Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult− StudentInfo:Code=001,Name=Zara,Age=9 StudentInfo:Code=001,Name=Zara,Age=10 UsefulVideoCourses Video 2DGamesDevelopmentusingUnityandC# 119Lectures 23.5hours RajaBiswas MoreDetail Video C#ConsoleandWindowsFormsDevelopmentwithLINQ&ADO.NET 37Lectures 13hours TrevoirWilliams MoreDetail Video FixingCommonErrorsinUnityC# 16Lectures 1hours PeterJepson MoreDetail Video ASP.NETCOREandC#RESTAPIWithRealWorldProjects 159Lectures 21.5hours EbenezerOgbu MoreDetail Video AutoCADProgrammingUsingC#.NET-BeginnerCourse 193Lectures 17hours ArnoldHiguit MoreDetail Video TheBeginner'sGuidetoC# 24Lectures 2.5hours EricFrick MoreDetail PreviousPage PrintPage NextPage  Advertisements Print  AddNotes  Bookmarkthispage  ReportError  Suggestions Save Close Dashboard Logout



請為這篇文章評分?