C# 中類的私有成員變數的範圍是什麼?


只有同一個類的函式可以訪問它的私有成員。私有訪問說明符允許類隱藏它的成員變數和成員函式,讓其他函式和物件訪問不到。

示例

 動態演示

using System;
namespace RectangleApplication {
   class Rectangle {
      //member variables
      private double length;
      private double width;
      public void Acceptdetails() {
         length = 10;
         width = 14;
      }
      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: 14
Area: 140

上面,變數 length 和 width 宣告為私有;因此同一類的函式可以訪問它。

更新於: 23-6 月-2020

328 次瀏覽

開啟你的職業生涯

完成本課程,獲得認證

立即開始
廣告
© . All rights reserved.