C# 中類的成員變數是什麼?


類是 C# 中有成員變數和函式的藍圖。它描述了物件的特徵。

讓我們看看類的語法,以便了解什麼是成員變數——

<access specifier> class class_name {
   // member variables
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list) {
      // method body
   }
   <access specifier> <return type> method2(parameter_list) {
      // method body
   }
   ...
   <access specifier> <return type> methodN(parameter_list) {
      // method body
   }
}

成員變數是從設計角度看物件的屬性,並且為了實現封裝而保持私有。只能使用公有成員函式來訪問這些變數。

下面的長度和寬度是成員變數,因為 Rectangle 類的每個新例項都會建立一個此變數的新例項。

例項

 線上演示

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

更新於:2020 年 6 月 20 日

4K+ 瀏覽次數

開啟您的事業

完成課程後獲得認證

開始
廣告
© . All rights reserved.