C# 中 public、protected 和 private 访问说明符之间有什么区别?

csharpprogrammingserver side programming更新于 2025/10/11 21:22:17

公共访问说明符

公共访问说明符允许类将其成员变量和成员函数暴露给其他函数和对象。任何公共成员都可以从类外部访问。

示例

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());
      }
   } //end class Rectangle
   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 受保护的访问修饰符

受保护的访问修饰符允许子类访问其基类的成员变量和成员函数。

让我们看一个使用受保护的访问修饰符访问受保护成员的示例。

示例

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 私有访问说明符

私有访问说明符允许类向其他函数和对象隐藏其成员变量和成员函数。只有同一类的函数才能访问其私有成员。即使是类的实例也无法访问其私有成员。

示例

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

输出

Length: 10
Width: 15
Area: 150

相关文章