Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Encapsulation (Đóng gói) trong C#


Encapsulation triển khai bằng access specifiers. Access specifier định nghĩa scope/visibility của class member. C# hỗ trợ: Public, Private, Protected, Internal, Protected internal.

Ví dụ private access specifier ẩn biến thành viên:

Ví dụ

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();
        }
    }
}