프로그래밍
기본 생성자는 C# 12에서 클래스 매개 변수를 추가합니다.
itssue-host
2023. 12. 3. 18:41
원문 : 기본 생성자는 C# 12에서 클래스 매개 변수를 추가합니다. (roundthecode.com)
Primary constructors adds class parameters in C# 12
Primary constructors is a C# 12 feature that allows to add parameters to a class and includes dependency injection support.
www.roundthecode.com
이제 readonly만 추가된다면 kotlin과 동일하게 사용됩니다.
기본 생성자를 사용하여 생성자 추가
기본 생성자를 사용하면 매개 변수 값을 포함해야 하므로 생성자를 추가해야 하는 방식이 변경됩니다. 그렇지 않으면 다음과 같은 빌드 예외가 발생합니다.
A constructor declared in a type with parameter list must have 'this' constructor initializer.
이를 위해 키워드를 포함하고 매개변수 값을 추가합니다.this
public class Employee(TimeSpan startTime, TimeSpan finishTime) {
public Employee() : this(new TimeSpan(9,0,0), new TimeSpan(17,0,0)) {
}
public TimeSpan GetStartTime() {
return startTime;
}
}