C# 中类的成员变量是什么?

csharpprogrammingserver side programming更新于 2025/10/15 17:37:17

类是 C# 中具有成员变量和函数的蓝图。它描述了对象的行为。

让我们通过类的语法来了解什么是成员变量 −

<access specifier> class class_name {
   // 成员变量
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list) {
      // 方法主体
   }
   <access specifier> <return type> method2(parameter_list) {
      // 方法主体
   }
   ...
   <access specifier> <return type> methodN(parameter_list) {
      // 方法主体
   }
}

成员变量是对象的属性(从设计角度来看),它们被保留为私有以实现封装。这些变量只能使用公共成员函数访问。

长度和宽度下方是成员变量,因为每个新的 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

相关文章