คลาสคือพิมพ์เขียวที่มีตัวแปรสมาชิกและฟังก์ชันในภาษา C# สิ่งนี้อธิบายพฤติกรรมของวัตถุ
ให้เราดูไวยากรณ์ของคลาสเพื่อเรียนรู้ว่าตัวแปรสมาชิกคืออะไร -
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) {
// method body
}
<access specifier> <return type> method2(parameter_list) {
// method body
}
...
<access specifier> <return type> methodN(parameter_list) {
// method body
}
} ตัวแปรสมาชิกเป็นแอตทริบิวต์ของวัตถุ (จากมุมมองของการออกแบบ) และจะถูกเก็บไว้เป็นส่วนตัวเพื่อใช้การห่อหุ้ม ตัวแปรเหล่านี้สามารถเข้าถึงได้โดยใช้ฟังก์ชันสมาชิกสาธารณะเท่านั้น
ความยาวและความกว้างด้านล่างเป็นตัวแปรสมาชิก เนื่องจากอินสแตนซ์ใหม่/ของตัวแปรนี้จะถูกสร้างขึ้นสำหรับอินสแตนซ์ใหม่ของคลาส Rectangle
ตัวอย่าง
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 14;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
} //end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
} ผลลัพธ์
Length: 10 Width: 14 Area: 140