C# Class and Objects - TutorialsTeacher
文章推薦指數: 80 %
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
延伸文章資訊
- 1C# Object and Class - Javatpoint
C# Class Example 4: Store and Display Employee Information · using System; · public class Employe...
- 2C# Class and Objects - TutorialsTeacher
A class can contain one or more constructors, fields, methods, properties, delegates, and events....
- 3C# 类(Class) - 菜鸟教程
C# 类(Class) 当你定义一个类时,你定义了一个数据类型的蓝图。 ... <access specifier> class class_name ... public Line(doubl...
- 4Classes - Microsoft Docs
The class keyword is preceded by the access level. Because public is used in this case, anyone ca...
- 5class 關鍵字- C# 參考
class TestClass { // Methods, properties, fields, events, delegates // and nested classes go here...