在 C# 中,類的公共成員變數的範圍是什麼?


公共訪問說明符允許類向其他函式和物件公開其成員變數和成員函式。可從類外訪問任何公共成員。

在下面示例中,length 和 width 變數已被宣告為公共。現在你甚至可以在 Main() 方法外訪問它們。

使用類的例項訪問這些變數。

Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;

我們來看看完整程式碼。

示例

Using System;
namespace RectangleApplication {
   class Rectangle {
      // member variables
      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 = 4.5;
         r.width = 3.5;
         r.Display();
         Console.ReadLine();
      }
   }
}

更新時間: 2020-06-23

瀏覽374次

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.