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

Khác biệt giữa public, protected, private trong C#

Public Access Specifier

Cho phép class public member variables/functions ra bên ngoài. Bất kỳ public member nào đều truy cập được từ ngoài class.

Ví dụ

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

Kết quả

Length: 7 Width: 10 Area: 70

Protected Access Specifier

Cho phép child class truy cập member variables/functions của base class.

Ví dụ

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

Kết quả

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

Private Access Specifier

Giấu member variables/functions khỏi class/function/object khác. Chỉ function cùng class mới truy cập được. Thậm chí instance cũng không truy cập được private member.

Ví dụ

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

Kết quả

Length: 10 Width: 15 Area: 150