생성자에서 매개변수를 추가할 수도 있습니다. 이러한 생성자를 매개변수화된 생성자라고 합니다. 이 기술은 생성 시 개체에 초기 값을 할당하는 데 도움이 됩니다.
다음은 예입니다 -
// class class Demo
매개변수 순위가 있는 매개변수화된 생성자 -
public Demo(int rank) {
Console.WriteLine("RANK = {0}", rank);
} 다음은 C#에서 매개변수화된 생성자로 작업하는 방법을 보여주는 완전한 예입니다 -
예
using System;
namespace Demo {
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