C# Class and Objects - TutorialsTeacher

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

A class can contain one or more constructors, fields, methods, properties, delegates, and events. They are called class members. A class and its members can ... C# ASP.NETCore MVC IoC TypeScript Angular Python SQLServer MongoDB More ✕ .NETTutorials C# ASP.NETCore ASP.NETMVC IoC WebAPI LINQ ClientSide JavaScript jQuery Node.js D3.js TypeScript Angular11 AngularJS1 Sass ServerSide Golang Python https SQL SQLServer PostgreSQL MongoDB SkillTests ASP.NETCore ASP.NETMVC LINQ C# webapi IoC TypeScript AngularJS Node.js jQuery JavaScript Articles Tests LearnC# C#-GetStarted C#-VersionHistory C#-FirstProgram C#-Keywords C#-Class C#-Namespace C#-Variable C#-Implicitly-TypedVariable C#-DataTypes Numbers Strings DateTime Structure Enum StringBuilder AnonymousTypes DynamicTypes NullableTypes C#-Value&ReferenceTypes C#-Interface C#-Operators C#-ifelseStatements C#-TernaryOperator?: C#-Switch C#-ForLoop C#-WhileLoop C#-Do-whileLoop C#-PartialClass C#-Static C#-Array MultidimensionalArray JaggedArray C#-Indexer C#-Generics GenericConstraints C#-Collections ArrayList List SortedList Dictionary Hashtable Stack Queue C#-Tuple C#-ValueTuple C#-Built-inExceptions ExceptionHandling throw CustomException C#-Delegates FuncDelegate ActionDelegate PredicateDelegate AnonymousMethods C#-Events C#-Covariance C#-ExtensionMethod C#-StreamI/O C#-File C#-FileInfo C#-ObjectInitializer C#-UsefulResources Previous Next C#ClassandObjects Aclassislikeablueprintofaspecificobjectthathascertainattributesandfeatures. Forexample,acarshouldhavesomeattributessuchasfourwheels,twoormoredoors,steering,awindshield,etc. Itshouldalsohavesomefunctionalitieslikestart,stop,run,move,etc. Now,anyobjectthathastheseattributesandfunctionalitiesisacar. Here,thecarisaclassthatdefinessomespecificattributesandfunctionalities.Eachindividualcarisanobjectofthecarclass. Youcansaythatthecaryouarehavingisanobjectofthecarclass. Likewise,inobject-orientedprogramming,aclassdefinessomeproperties,fields,events,methods,etc.Aclassdefinesthekindsofdataandthefunctionalitytheirobjectswillhave. DefineaClass InC#,aclasscanbedefinedbyusingtheclasskeyword. Let'sdefineaclassnamed'Student'. Example:DefineaClass classStudent { } Aclasscancontainoneormoreconstructors,fields,methods,properties,delegates,andevents.Theyarecalledclassmembers. Aclassanditsmemberscanhaveaccessmodifierssuchaspublic,private,protected,andinternal,torestrictaccessfromotherpartsoftheprogram. Let'sadddifferentmemberstotheStudentclass. Field Aclasscanhaveoneormorefields.Itisaclass-levelvariablethatholdsavalue.Generally,fieldmembersshouldhaveaprivateaccessmodifierusedwithproperty. Example:Field classStudent { publicintid; } Property Apropertyencapsulatesaprivatefieldusingsetterandgettertoassignandretrieveunderlyingfieldvalue. Example:Property classStudent { privateintid; publicintStudentId { get{returnid;} set{id=value;} } } Intheaboveexample,theidisaprivatefieldthatcannotbeaccesseddirectly.ItwillonlybeaccessedusingtheStudentIdproperty. Theget{}returnsthevalueoftheunderlyingfieldandset{}assignsthevaluetotheunderlyingfieldid. Youcanalsoapplysomeadditionallogicingetandset,asinthebelowexample. Example:PropertyinC# privateintid; publicintStudentId { get{returnid;} set{ if(value>0) id=value; } } Auto-implementedProperty FromC#3.0onwards,propertydeclarationhasbeenmadeeasyifyoudon'twanttoapplysomelogicingetterorsetter.Usingauto-implementedproperty,youdon'tneedtodeclareanunderlyingprivatefield. C#compilerwillautomaticallycreateitinILcode. Example:Auto-implementedProperty classStudent { publicstringFirstName{get;set;} publicstringLastName{get;set;} } Intheaboveexample,backingprivatefieldfortheFirstNameandLastNamewillbecreatedinternallybythecompiler.Thisspeedupthedevelopmenttimeandcodereadability. Method Amethodcancontainoneormorestatementstobeexecutedasasingleunit.Amethodmayormaynotreturnavalue.Amethodcanhaveoneormoreinputparameters. Syntax [access-modifier]return-typeMethodName(typeparameterName1,typeparameterName2,...) { } ThefollowingdefinestheSummethodthatreturnsthesumoftwonumbers. Example:C#Method publicintSum(intnum1,intnum2) { vartotal=num1+num2; returntotal; } Thefollowingmethoddoesn'treturnanythinganddoesn'thaveanyparameters.Thereturntypeisvoid. Example:C#Method publicvoidGreet() { Console.Write("HelloWorld!"); } ThefollowingdefinestheGetFullName()methodintheStudentclass. Example:Method classStudent { publicstringFirstName{get;set;} publicstringLastName{get;set;} publicstringGetFullName() { returnFirstName+""+LastName; } } Constructor Aconstructorisaspecialtypeofmethodwhichwillbecalledautomaticallywhenyoucreateaninstanceofaclass. Aconstructorisdefinedbyusinganaccessmodifierandclassname(){}. Example:Constructor classStudent { publicStudent() { //constructor } } Aconstructornamemustbethesameasaclassname. Aconstructorcanbepublic,private,orprotected. Theconstructorcannotreturnanyvaluesocannothaveareturntype. Aclasscanhavemultipleconstructorswithdifferentparametersbutcanonlyhaveoneparameterlessconstructor. Ifnoconstructorisdefined,theC#compilerwouldcreateitinternally. ObjectsofaClass Youcancreateoneormoreobjectsofaclass.Eachobjectcanhavedifferentvaluesofpropertiesandfieldbutmethodsandeventsbehavesthesame. InC#,anobjectofaclasscanbecreatedusingthenewkeywordandassignthatobjecttoavariableofaclasstype. Forexample,thefollowingcreatesanobjectoftheStudentclassandassignittoavariableoftheStudenttype. Example:CreateanObjectofaClass Studentmystudent=newStudent(); Youcannowaccesspublicmembersofaclassusingtheobject.MemberNamenotation. Example:AccessMembersofaClass Studentmystudent=newStudent(); mystudent.FirstName="Steve"; mystudent.LastName="Jobs"; mystudent.GetFullName(); Youcancreatemultipleobjectsofaclasswithdifferentvaluesofpropertiesandfields. Example:CreateMultipleObjectsofaClass Studentmystudent1=newStudent(); mystudent1.FirstName="Steve"; mystudent1.LastName="Jobs"; Studentmystudent2=newStudent(); mystudent2.FirstName="Bill"; mystudent2.LastName="Gates"; C#Questions&Answers StartC#SkillTest RelatedArticles ForeachLoopinC# DesignPrinciplevsDesignPattern DifferencebetweenArrayandArrayList DifferencebetweenHashtableandDictionary HowtowritefileusingStreamWriterinC#? HowtosortthegenericSortedListinthedescendingorder? DifferencebetweendelegatesandeventsinC# HowtoreadfileusingStreamReaderinC#? HowtocalculatethecodeexecutiontimeinC#? HowtoconvertstringtointinC#? BoxingandUnboxinginC# MoreC#articles Previous Next Share Tweet Share Whatsapp C#Questions&Answers C#SkillTest C#LatestArticles



請為這篇文章評分?