Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

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