programing tip

같은 클래스의 다른 생성자에서 생성자 호출

itbloger 2020. 6. 26. 18:55
반응형

같은 클래스의 다른 생성자에서 생성자 호출


생성자가 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

반응형