산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# - 클래스

클래스를 정의할 때 데이터 유형에 대한 청사진을 정의합니다. 이것은 실제로 어떤 데이터도 정의하지 않지만 클래스 이름이 의미하는 바를 정의합니다. 즉, 클래스의 개체가 무엇으로 구성되어 있고 해당 개체에서 수행할 수 있는 작업이 무엇인지입니다. 객체는 클래스의 인스턴스입니다. 클래스를 구성하는 메소드와 변수를 클래스의 멤버라고 합니다.

클래스 정의

클래스 정의는 class 키워드 뒤에 클래스 이름이 오는 것으로 시작합니다. 한 쌍의 중괄호로 묶인 클래스 본문. 다음은 클래스 정의의 일반적인 형식입니다. -

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

참고 -

다음 예는 지금까지 논의된 개념을 보여줍니다 -

라이브 데모
using System;

namespace BoxApplication {
   class Box {
      public double length;   // Length of a box
      public double breadth;  // Breadth of a box
      public double height;   // Height of a box
   }
   class Boxtester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();   // Declare Box2 of type Box
         double volume = 0.0;    // Store the volume of a box here

         // box 1 specification
         Box1.height = 5.0;
         Box1.length = 6.0;
         Box1.breadth = 7.0;

         // box 2 specification
         Box2.height = 10.0;
         Box2.length = 12.0;
         Box2.breadth = 13.0;
           
         // volume of box 1
         volume = Box1.height * Box1.length * Box1.breadth;
         Console.WriteLine("Volume of Box1 : {0}",  volume);

         // volume of box 2
         volume = Box2.height * Box2.length * Box2.breadth;
         Console.WriteLine("Volume of Box2 : {0}", volume);
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Volume of Box1 : 210
Volume of Box2 : 1560

멤버 함수 및 캡슐화

클래스의 멤버 함수는 다른 변수와 유사한 클래스 정의 내에 해당 정의 또는 프로토타입이 있는 함수입니다. 이는 자신이 구성원인 클래스의 모든 개체에서 작동하며 해당 개체에 대한 클래스의 모든 구성원에 액세스할 수 있습니다.

멤버 변수는 (디자인 관점에서) 개체의 속성이며 캡슐화를 구현하기 위해 비공개로 유지됩니다. 이러한 변수는 공용 멤버 함수를 통해서만 액세스할 수 있습니다.

클래스의 다른 클래스 멤버의 값을 설정하고 가져오기 위해 위의 개념을 적용해 보겠습니다. −

라이브 데모
using System;

namespace BoxApplication {
   class Box {
      private double length;   // Length of a box
      private double breadth;  // Breadth of a box
      private double height;   // Height of a box
      
      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }
      public double getVolume() {
         return length * breadth * height;
      }
   }
   class Boxtester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;
         
         // Declare Box2 of type Box
         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);
         
         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);
         
         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);
         
         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);
         
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Volume of Box1 : 210
Volume of Box2 : 1560

C# 생성자

클래스 생성자 는 해당 클래스의 새 개체를 만들 때마다 실행되는 클래스의 특수 멤버 함수입니다.

생성자는 클래스의 이름과 정확히 같은 이름을 가지며 반환 유형이 없습니다. 다음 예제는 생성자의 개념을 설명합니다 -

라이브 데모
using System;

namespace LineApplication {
   class Line {
      private double length;   // Length of a line
      
      public Line() {
         Console.WriteLine("Object is being created");
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }

      static void Main(string[] args) {
         Line line = new Line();    
         
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Object is being created
Length of line : 6

기본 생성자 매개변수가 없지만 필요한 경우 생성자가 매개변수를 가질 수 있습니다. 이러한 생성자를 매개변수화된 생성자라고 합니다. . 이 기술은 다음 예제와 같이 생성 시 객체에 초기 값을 할당하는 데 도움이 됩니다. -

라이브 데모
using System;

namespace LineApplication {
   class Line {
      private double length;   // Length of a line
      
      public Line(double len) {  //Parameterized constructor
         Console.WriteLine("Object is being created, length = {0}", len);
         length = len;
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }
      static void Main(string[] args) {
         Line line = new Line(10.0);
         Console.WriteLine("Length of line : {0}", line.getLength()); 
         
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength()); 
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Object is being created, length = 10
Length of line : 10
Length of line : 6

C# 소멸자

소멸자 클래스의 개체가 범위를 벗어날 때마다 실행되는 클래스의 특수 멤버 함수입니다. 소멸자 접두사(~)가 붙은 클래스의 이름과 정확히 같으며 값을 반환하거나 매개변수를 사용할 수 없습니다.

소멸자는 프로그램을 종료하기 전에 메모리 리소스를 해제하는 데 매우 유용할 수 있습니다. 소멸자는 상속되거나 오버로드될 수 없습니다.

다음 예제는 소멸자의 개념을 설명합니다 -

라이브 데모
using System;

namespace LineApplication {
   class Line {
      private double length;   // Length of a line
      
      public Line() {   // constructor
         Console.WriteLine("Object is being created");
      }
      ~Line() {   //destructor
         Console.WriteLine("Object is being deleted");
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }
      static void Main(string[] args) {
         Line line = new Line();

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());           
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Object is being created
Length of line : 6
Object is being deleted

C# 클래스의 정적 멤버

static을 사용하여 클래스 멤버를 static으로 정의할 수 있습니다. 예어. 클래스의 멤버를 static으로 선언하면 클래스의 객체가 아무리 많이 생성되더라도 static 멤버의 복사본은 하나만 있다는 의미입니다.

키워드 정적 클래스에 대해 멤버의 인스턴스가 하나만 존재함을 의미합니다. 정적 변수는 인스턴스를 만들지 않고 클래스를 호출하여 값을 검색할 수 있기 때문에 상수를 정의하는 데 사용됩니다. 정적 변수는 멤버 함수 또는 클래스 정의 외부에서 초기화할 수 있습니다. 클래스 정의 내에서 정적 변수를 초기화할 수도 있습니다.

다음 예는 정적 변수의 사용을 보여줍니다. -

라이브 데모
using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;
      
      public void count() {
         num++;
      }
      public int getNum() {
         return num;
      }
   }
   class StaticTester {
      static void Main(string[] args) {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();
         
         s1.count();
         s1.count();
         s1.count();
         
         s2.count();
         s2.count();
         s2.count();
         
         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Variable num for s1: 6
Variable num for s2: 6

멤버 함수를 선언할 수도 있습니다. 정적으로 . 이러한 함수는 정적 변수에만 액세스할 수 있습니다. 정적 함수는 객체가 생성되기 전에도 존재합니다. 다음 예는 정적 함수의 사용을 보여줍니다. -

라이브 데모
using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;
      
      public void count() {
         num++;
      }
      public static int getNum() {
         return num;
      }
   }
   class StaticTester {
      static void Main(string[] args) {
         StaticVar s = new StaticVar();
         
         s.count();
         s.count();
         s.count();
         
         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Variable num: 3

C 언어

  1. C# 클래스 및 개체
  2. C# 액세스 수정자
  3. C# 정적 키워드
  4. C# 추상 클래스 및 메서드
  5. C# 중첩 클래스
  6. C++ 클래스 및 개체
  7. C - 스토리지 클래스
  8. C++의 스토리지 클래스
  9. C++의 인터페이스(추상 클래스)
  10. C# - 프로그램 구조