생성자
클래스 생성자는 해당 클래스의 새 객체를 생성할 때마다 실행되는 클래스의 특수 멤버 함수입니다.
생성자는 클래스와 이름이 정확히 같으며 반환 유형이 없습니다.
생성자는 클래스 이름과 동일한 이름을 가집니다 -
class Demo {
public Demo() {}
} 다음은 예입니다 -
예시
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
소멸자
소멸자는 클래스의 개체가 범위를 벗어날 때마다 실행되는 클래스의 특수 멤버 함수입니다. 값을 반환하거나 매개변수를 사용할 수 없습니다.
접두사 물결표(~)가 붙은 클래스의 이름과 정확히 같은 이름을 갖습니다. 예를 들어 클래스 이름은 Demo −
입니다.public Demo() { // constructor
Console.WriteLine("Object is being created");
}
~Demo() { //destructor
Console.WriteLine("Object is being deleted");
} 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