Computer >> Máy Tính >  >> Lập trình >> C#

Các biến thành viên của một lớp trong C # là gì?

Một lớp là một bản thiết kế có các biến và hàm thành viên trong C #. Điều này mô tả hành vi của một đối tượng.

Hãy để chúng tôi xem cú pháp của một lớp để tìm hiểu các biến thành viên là gì -

<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
   }
}

Các biến thành viên là các thuộc tính của một đối tượng (từ quan điểm thiết kế) và chúng được giữ kín để thực hiện đóng gói. Các biến này chỉ có thể được truy cập bằng các hàm thành viên công khai.

Bên dưới chiều dài và chiều rộng là các biến thành viên vì một phiên bản mới / của biến này sẽ được tạo cho mỗi phiên bản mới của lớp Rectangle.

Ví dụ

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();
      }
   }
}

Đầu ra

Length: 10
Width: 14
Area: 140