클래스 생성자는 해당 클래스의 새 객체를 생성할 때마다 실행되는 클래스의 특수 멤버 함수입니다. 기본 생성자에는 매개변수가 없습니다.
다음은 C#에서 기본 생성자로 작업하는 방법을 보여주는 예입니다 -
예시
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