Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่าง public, protected และ private ใน C#

Public Access Specifier

Public อนุญาตให้คลาสเปิดเผยตัวแปรสมาชิกและฟังก์ชันสมาชิกให้ฟังก์ชันและอ็อบเจกต์อื่นเข้าถึงได้ สมาชิก public เข้าถึงได้จากภายนอกคลาส

ตัวอย่าง

using System; 
namespace Demo { 
    class Rectangle { 
        public double length; 
        public double width; 
        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.length = 7; r.width = 10; r.Display(); 
            Console.ReadLine(); 
        } 
    } 
}

ผลลัพธ์

Length: 7 Width: 10 Area: 70

Protected Access Specifier

Protected อนุญาตให้คลาสลูกเข้าถึงตัวแปรและฟังก์ชันของคลาสฐานได้

ตัวอย่าง

using System; 
namespace MySpecifiers { 
    class Demo { 
        protected string name = "Website"; 
        protected void Display(string str) { Console.WriteLine("Tabs: " + str); } 
    } 
    class Test : Demo { 
        static void Main(string[] args) { 
            Test t = new Test(); 
            Console.WriteLine("Details: " + t.name); 
            t.Display("Product"); t.Display("Services"); t.Display("Tools"); t.Display("Plugins"); 
        } 
    } 
}

ผลลัพธ์

Details: Website Tabs: Product Tabs: Services Tabs: Tools Tabs: Plugins

Private Access Specifier

Private ซ่อนตัวแปรและฟังก์ชันจากฟังก์ชันและอ็อบเจกต์อื่น เฉพาะฟังก์ชันในคลาสเดียวกันเท่านั้นที่เข้าถึงได้ แม้อินสแตนซ์ของคลาสก็ไม่เข้าถึง private ได้

ตัวอย่าง

using System; 
namespace Demo { 
    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(); 
        } 
    } 
}

ผลลัพธ์

Length: 10 Width: 15 Area: 150