การห่อหุ้มใน C # ป้องกันการเข้าถึงรายละเอียดการใช้งาน ใช้การห่อหุ้มใน C # โดยใช้ตัวระบุการเข้าถึง
ต่อไปนี้เป็นตัวระบุการเข้าถึงที่รองรับโดย C#
- สาธารณะ
- ส่วนตัว
- ได้รับการปกป้อง
- ภายใน
- ป้องกันภายใน
การห่อหุ้มสามารถเข้าใจได้โดยใช้ตัวอย่างของตัวระบุการเข้าถึงส่วนตัวที่ช่วยให้คลาสสามารถซ่อนตัวแปรสมาชิกและฟังก์ชันสมาชิกจากฟังก์ชันและอ็อบเจ็กต์อื่นได้
ในตัวอย่างต่อไปนี้ เรามีความยาวและความกว้างเป็นตัวแปรที่กำหนดตัวระบุการเข้าถึงส่วนตัว
ตัวอย่าง
using System;
namespace RectangleApplication {
class Rectangle {
private double length;
private double width;
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