C# - Properties - Tutorialspoint
文章推薦指數: 80 %
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
延伸文章資訊
- 1[C#.NET] 使用屬性(Property) 的好處| 余小章@ 大內殿堂- 點部落
[C#.NET] 使用屬性(Property) 的好處. 我相信很多人寫很久的程式從沒有習慣使用property,甚至連property 是什麼都不知道,長期以來都是一直 ...
- 2屬性- C# 程式設計手冊
_seconds = value * 3600; } } } class Program { static void Main() { TimePeriod t = new TimePeriod...
- 3Properties In C#
Property in C# is a member of a class that provides a flexible mechanism for classes to expose pr...
- 4C# 属性(Property) | 菜鸟教程
C# 属性(Property) 属性(Property) 是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为域(F...
- 5屬性(Property) 與欄位(Field) - mrkt 的程式學習筆記
Property:FullDescription為主要資料取得的地方,對外公開;. Field:_FullDescription為物件私有成員,是用來存放屬性的資料。 MSDN - 使用屬性(C...