Encapsulation คือการซ่อนรายละเอียดการทำงานภายใน (Implementation Details) และเปิดเผยเฉพาะสิ่งที่จำเป็น ผ่าน Access Specifiers
Access Specifiers ใน C#
| Specifier | ขอบเขตการเข้าถึง |
|---|---|
| public | เข้าถึงได้จากทุกที่ |
| private | เข้าถึงได้เฉพาะในคลาสเดียวกัน (ค่าเริ่มต้น) |
| protected | เข้าถึงได้ในคลาสเดียวกันและคลาสลูก |
| internal | เข้าถึงได้ใน Assembly เดียวกัน |
| protected internal | protected หรือ internal |
| private protected | protected และ internal (C# 7.2+) |
ตัวอย่าง: ใช้ private ซ่อนข้อมูล
using System;
namespace RectangleApplication
{
class Rectangle
{
private double length;
private double width;
public void AcceptDetails()
{
length = 20;
width = 30;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.AcceptDetails();
r.Display();
Console.ReadLine();
}
}
}
ผลลัพธ์
Length: 20 Width: 30 Area: 600
ประโยชน์
- ควบคุมการเข้าถึงข้อมูล (Validation ใน Setter)
- ซ่อนความซับซ้อนภายใน
- ลด Coupling ระหว่างคลาส