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

Encapsulation (การห่อหุ้ม) ใน C#: การปกป้องข้อมูล

Encapsulation (การห่อหุ้ม) เป็นหลักการสำคัญของ OOP ใน C# ใช้เพื่อปกป้องข้อมูลภายในคลาส ไม่ให้เข้าถึงหรือเปลี่ยนแปลงโดยตรงจากภายนอก ทำผ่าน Access Specifiers (ตัวระบุการเข้าถึง)

Access Specifiers ใน C#

Modifierขอบเขตการเข้าถึง
publicเข้าถึงได้จากทุกที่
privateเข้าถึงได้เฉพาะในคลาสเดียวกัน (Default สำหรับ class members)
protectedเข้าถึงได้ในคลาสเดียวกันและคลาสลูก
internalเข้าถึงได้ใน Assembly เดียวกัน (Default สำหรับ class)
protected internalเข้าถึงได้ใน Assembly เดียวกัน OR คลาสลูก (Union)
private protectedเข้าถึงได้ใน Assembly เดียวกัน AND คลาสลูก (Intersection) - C# 7.2+

ตัวอย่าง: ใช้ private กับ Property

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() => length * width;
        
        public void Display()
        {
            Console.WriteLine($"ความยาว: {length}");
            Console.WriteLine($"ความกว้าง: {width}");
            Console.WriteLine($"พื้นที่: {GetArea()}");
        }
    }
    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.AcceptDetails(); // ตั้งค่าผ่าน Method
            r.Display();       // อ่านค่าผ่าน Method
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

ความยาว: 10
ความกว้าง: 15
พื้นที่: 150

แนวทางปฏิบัติที่ดี (Modern C#)

ใช้ Auto-implemented Properties แทน Private Field + Public Method:

public class Rectangle
{
    public double Length { get; private set; }
    public double Width { get; private set; }
    
    public double Area => Length * Width; // Expression-bodied property
    
    public void SetDimensions(double length, double width)
    {
        if (length <= 0 || width <= 0)
            throw new ArgumentException("Dimensions must be positive");
        
        Length = length;
        Width = width;
    }
}

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

  • Data Hiding: ซ่อนรายละเอียดการทำงานภายใน
  • Validation: ตรวจสอบค่าก่อนตั้งค่า
  • Flexibility: เปลี่ยน Implementation ภายในโดยไม่กระทบ Caller
  • Security: ป้องกันการตั้งค่าที่ไม่ถูกต้อง