캡슐화는 액세스 지정자를 사용하여 구현됩니다. 액세스 지정자는 클래스 멤버의 범위와 가시성을 정의합니다. C#은 Public, Private, Protected, Internal, Protected internal 등의 액세스 지정자를 지원합니다.
캡슐화는 클래스가 자신의 멤버 변수와 멤버 함수를 다른 함수 및 개체로부터 숨길 수 있도록 하는 비공개 액세스 지정자의 예를 통해 이해할 수 있습니다.
다음 예에서 우리는 길이와 너비를 변수로 할당된 개인 액세스 지정자 −
를 가집니다.예
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();
}
}
}