Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การทำ Encapsulation ใน C# อย่างไร

Encapsulation คือการซ่อนรายละเอียดการทำงานภายใน (Implementation Details) และเปิดเผยเฉพาะสิ่งที่จำเป็น ผ่าน Access Specifiers

Access Specifiers ใน C#

Specifierขอบเขตการเข้าถึง
publicเข้าถึงได้จากทุกที่
privateเข้าถึงได้เฉพาะในคลาสเดียวกัน (ค่าเริ่มต้น)
protectedเข้าถึงได้ในคลาสเดียวกันและคลาสลูก
internalเข้าถึงได้ใน Assembly เดียวกัน
protected internalprotected หรือ internal
private protectedprotected และ 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 ระหว่างคลาส