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

Encapsulation ใน C# คืออะไร

Encapsulation (การห่อหุ้ม) คือการรวม Data (Fields) และ Behavior (Methods) ไว้ใน Class เดียวกัน และควบคุมการเข้าถึงผ่าน Access Specifiers

Access Specifiers

SpecifierVisibility
publicทุกที่
privateใน Class เดียวกัน (Default)
protectedClass เดียวกัน + Derived Classes
internalAssembly เดียวกัน
protected internalProtected OR Internal
private protectedProtected AND Internal (C# 7.2+)

ตัวอย่าง: ใช้ private Fields + Public Properties/Methods

using System;

namespace RectangleApplication
{
    class Rectangle
    {
        // Private Fields - ซ่อนข้อมูล
        private double length;
        private double width;
        
        // Public Methods - Interface สำหรับเข้าถึง
        public void AcceptDetails()
        {
            length = 10;
            width = 15;
        }
        
        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: 10
Width: 15
Area: 150

Properties (Modern Encapsulation)

class Rectangle
{
    private double _length;
    
    public double Length
    {
        get => _length;
        set
        {
            if (value <= 0)
                throw new ArgumentException("Length must be positive");
            _length = value;
        }
    }
}

ประโยชน์ของ Encapsulation

  • Data Hiding - ซ่อน Implementation Details
  • Validation - ตรวจสอบค่าก่อน Set (ใน Setter)
  • Flexibility - เปลี่ยน Internal Implementation โดยไม่กระทบ Caller
  • Control - Read-only, Write-only, Lazy Loading ได้