같은 클래스의 다른 생성자에서 생성자 호출
생성자가 2 개인 클래스가 있습니다.
public class Lens
{
public Lens(string parameter1)
{
//blabla
}
public Lens(string parameter1, string parameter2)
{
// want to call constructor with 1 param here..
}
}
두 번째 생성자에서 첫 번째 생성자를 호출하고 싶습니다. C #에서 가능합니까?
:this(required params)
생성자 끝에 추가 하여 '생성자 체인'을 수행하십시오.
public Test( bool a, int b, string c )
: this( a, b )
{
this.m_C = c;
}
public Test( bool a, int b, float d )
: this( a, b )
{
this.m_D = d;
}
private Test( bool a, int b )
{
this.m_A = a;
this.m_B = b;
}
csharp411.com의 소스 제공
예, 다음을 사용합니다
public class Lens
{
public Lens(string parameter1)
{
//blabla
}
public Lens(string parameter1, string parameter2) : this(parameter1)
{
}
}
생성자를 연결할 때 생성자 평가 순서도 고려해야합니다.
Gishu의 답변에서 빌리려면 약간의 코드를 유지하십시오.
public Test(bool a, int b, string c)
: this(a, b)
{
this.C = c;
}
private Test(bool a, int b)
{
this.A = a;
this.B = b;
}
private
생성자 에서 수행 된 증발을 약간 변경하면 생성자 순서가 중요한 이유를 알 수 있습니다.
private Test(bool a, int b)
{
// ... remember that this is called by the public constructor
// with `this(...`
if (hasValue(this.C))
{
// ...
}
this.A = a;
this.B = b;
}
Above, I have added a bogus function call that determines whether property C
has a value. At first glance, it might seem that C
would have a value -- it is set in the calling constructor; however, it is important to remember that constructors are functions.
this(a, b)
is called - and must "return" - before the public
constructor's body is performed. Stated differently, the last constructor called is the first constructor evaluated. In this case, private
is evaluated before public
(just to use the visibility as the identifier).
참고URL : https://stackoverflow.com/questions/829870/calling-constructor-from-other-constructor-in-same-class
'programing tip' 카테고리의 다른 글
Rails 직렬화를 사용하여 해시를 데이터베이스에 저장 (0) | 2020.06.26 |
---|---|
참조 자바 스크립트가없는 객체 복제 (0) | 2020.06.26 |
numpy 배열이 비어 있는지 여부를 어떻게 확인할 수 있습니까? (0) | 2020.06.26 |
URL과 파일 이름을 안전하게하기 위해 문자열을 삭제 하시겠습니까? (0) | 2020.06.26 |
CSV에서 큰 따옴표를 올바르게 이스케이프 처리 (0) | 2020.06.26 |