การห่อหุ้มจะดำเนินการโดยใช้ตัวระบุการเข้าถึง ตัวระบุการเข้าถึงกำหนดขอบเขตและการมองเห็นของสมาชิกคลาส C# รองรับตัวระบุการเข้าถึงต่อไปนี้:สาธารณะ ส่วนตัว ป้องกัน ภายใน ป้องกันภายใน ฯลฯ
การห่อหุ้มสามารถเข้าใจได้โดยยกตัวอย่างของตัวระบุการเข้าถึงส่วนตัวที่ช่วยให้คลาสสามารถซ่อนตัวแปรสมาชิกและฟังก์ชันของสมาชิกจากฟังก์ชันและอ็อบเจ็กต์อื่นๆ
ในตัวอย่างต่อไปนี้ เรามีความยาวและความกว้างเป็นตัวแปรที่กำหนดตัวระบุการเข้าถึงส่วนตัว -
ตัวอย่าง
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();
}
}
}