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

更新於: 20 年 6 月 20 日

4K+ 觀看次數

啟動你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.