Encapsulation trong C# ngăn chặn truy cập chi tiết triển khai. Triển khai Encapsulation dùng access specifiers (chỉ định truy cập).
Các access specifiers C# hỗ trợ:
- Public
- Private
- Protected
- Internal
- Protected internal
Encapsulation hiểu qua ví dụ private access specifier cho phép class ẩn biến thành viên và hàm thành viên khỏi hàm/đối tượng khác.
Ví dụ length và width có private access specifier:
Ví dụ
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();
}
}
}
Kết quả
Length: 10
Width: 15
Area: 150