C# Properties (Get and Set) - W3Schools
文章推薦指數: 80 %
C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; ... Tutorials References Exercises Videos Menu Login PaidCourses WebsiteNEW ProNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C++ C# R React Kotlin Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz XMLQuiz CyberSecurityQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro C#Tutorial C#HOME C#Intro C#GetStarted C#Syntax C#Comments C#Variables C#DataTypes C#TypeCasting C#UserInput C#Operators C#Math C#Strings C#Booleans C#If...Else C#Switch C#WhileLoop C#ForLoop C#Break/Continue C#Arrays C#Methods C#Methods C#MethodParameters C#MethodOverloading C#Classes C#OOP C#Classes/Objects C#ClassMembers C#Constructors C#AccessModifiers C#Properties C#Inheritance C#Polymorphism C#Abstraction C#Interface C#Enums C#Files C#Exceptions C#HowTo AddTwoNumbers C#Examples C#Examples C#Compiler C#Exercises C#Quiz C#Properties(GetandSet) ❮Previous Next❯ PropertiesandEncapsulation Beforewestarttoexplainproperties,youshouldhaveabasicunderstandingof"Encapsulation". ThemeaningofEncapsulation,istomakesurethat"sensitive"dataishidden fromusers.Toachievethis,youmust: declarefields/variablesasprivate providepublicget andsetmethods,throughproperties,toaccessandupdatethevalueofaprivate field Properties Youlearnedfromthepreviouschapterthatprivatevariablescanonlybe accessedwithinthesameclass(anoutsideclasshasnoaccesstoit).However, sometimesweneedtoaccessthem-anditcanbedonewithproperties. Apropertyislikeacombinationofavariableandamethod,andithastwomethods:agetandasetmethod: Example classPerson { privatestringname;//field publicstringName//property { get{returnname;}//getmethod set{name=value;}//setmethod } } Exampleexplained TheNamepropertyisassociatedwiththenamefield.Itisagoodpracticetousethesamenameforboththepropertyandtheprivatefield,butwithanuppercasefirstletter. Thegetmethodreturnsthevalueofthevariablename. Thesetmethodassignsavaluetothe namevariable.Thevaluekeywordrepresentsthevalueweassigntotheproperty. Ifyoudon'tfullyunderstandit,takealookattheexamplebelow. NowwecanusetheNamepropertytoaccessandupdatetheprivatefieldofthePersonclass: Example classPerson { privatestringname;//field publicstringName//property { get{returnname;} set{name=value;} } } classProgram { staticvoidMain(string[]args) { PersonmyObj=newPerson(); myObj.Name="Liam"; Console.WriteLine(myObj.Name); } } Theoutputwillbe: Liam TryitYourself» AutomaticProperties(ShortHand) C#alsoprovidesawaytouseshort-hand/automaticproperties,whereyoudo nothavetodefinethefieldfortheproperty,andyouonlyhavetowriteget; andset;insidetheproperty. Thefollowingexamplewillproducethesameresultastheexampleabove.Theonlydifferenceisthatthereislesscode: Example Usingautomaticproperties: classPerson { publicstringName//property {get;set;} } classProgram { staticvoidMain(string[]args) { PersonmyObj=newPerson(); myObj.Name="Liam"; Console.WriteLine(myObj.Name); } } Theoutputwillbe: Liam TryitYourself» WhyEncapsulation? Bettercontrolofclassmembers(reducethepossibilityofyourself(orothers)tomessupthecode) Fieldscanbemaderead-only(ifyouonlyusethegetmethod),orwrite-only(ifyouonlyusethesetmethod) Flexible:theprogrammercanchangeonepartofthecodewithoutaffectingotherparts Increasedsecurityofdata ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1C# 属性(Property) | 菜鸟教程
C# 属性(Property) 属性(Property) 是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为域(F...
- 2[C#.NET] 使用屬性(Property) 的好處| 余小章@ 大內殿堂- 點部落
[C#.NET] 使用屬性(Property) 的好處. 我相信很多人寫很久的程式從沒有習慣使用property,甚至連property 是什麼都不知道,長期以來都是一直 ...
- 3屬性(Property) 與欄位(Field) - mrkt 的程式學習筆記
Property:FullDescription為主要資料取得的地方,對外公開;. Field:_FullDescription為物件私有成員,是用來存放屬性的資料。 MSDN - 使用屬性(C...
- 4C# | Properties - GeeksforGeeks
Properties are the special type of class members that provides a flexible mechanism to read, writ...
- 5Properties In C#
Property in C# is a member of a class that provides a flexible mechanism for classes to expose pr...