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

Khác biệt giữa internal và private modifier trong C#


Internal Access Specifier

Cho phép truy cập từ bất kỳ lớp/phương thức nào trong cùng assembly.

Ví dụ Internal

using System;
namespace RectangleApplication {
    class Rectangle {
        internal double length;
        internal double width;
        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.length = 4.5; r.width = 3.5;
            r.Display(); Console.ReadLine();
        }
    }
}

Private Access Specifier

Ẩn thành viên khỏi lớp khác. Chỉ hàm cùng lớp truy cập.

Ví dụ Private

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