C# 中 public、protected 和 private 訪問限定符之間有什麼區別?


Public 訪問限定符

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());
      }
   } //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 訪問限定符

protected 訪問限定符允許子類訪問其父類的成員變數和成員函式。

讓我們看一個受保護訪問限定符的示例,該示例訪問 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 訪問限定符

private 訪問限定符允許類將它的成員變數和成員函式隱藏起來,不對其他函式和物件開放。只有該類的函式才能訪問它的 private 成員。即使該類的例項也不能訪問其 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

更新日期: 2020 年 6 月 23 日

3K+ 瀏覽

助力您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.