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

Quyền truy cập mặc định cho class trong C#

Nếu không chỉ định access modifier, mặc định là Internal. Internal cho phép class expose member variables/functions cho các hàm/đối tượng trong assembly hiện tại. Tức là member internal có thể truy cập từ bất kỳ class/method nào trong ứng dụng định nghĩa member đó.

Ví dụ minh họa Internal access specifier:

Ví dụ

using System; 
namespace RectangleApplication { 
    class Rectangle { 
        // member variables 
        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()); 
        } 
    } // end class Rectangle 
    class ExecuteRectangle { 
        static void Main(string[] args) { 
            Rectangle r = new Rectangle(); 
            r.length = 4.5; 
            r.width = 3.5; 
            r.Display(); 
            Console.ReadLine(); 
        } 
    } 
}

Kết quả

Length: 4.5
Width: 3.5
Area: 15.75