从同一个类中的另一个构造函数调用构造函数

时间:2009-05-06 14:25:59

标签: c# constructor

我有一个包含2个构造函数的类:

public class Lens
{
    public Lens(string parameter1)
    {
        //blabla
    }

    public Lens(string parameter1, string parameter2)
    {
       // want to call constructor with 1 param here..
    }
}

我想从第二个调用第一个构造函数。这在C#中是否可行?

3 个答案:

答案 0 :(得分:213)

在构造函数的末尾附加: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

答案 1 :(得分:31)

是的,您将使用以下

public class Lens
{
    public Lens(string parameter1)
    {
       //blabla
    }

    public Lens(string parameter1, string parameter2) : this(parameter1)
    {

    }
}

答案 2 :(得分:13)

链接构造函数时,还必须考虑构造函数求值的顺序:

从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;
}

上面,我添加了一个伪造函数调用,用于确定属性C是否具有值。乍一看,C似乎有一个值 - 它在调用构造函数中设置;但是,重要的是要记住构造函数是函数。

this(a, b)被调用 - 并且必须“返回” - 在public构造函数的主体执行之前。换句话说,最后一个被调用的构造函数是第一个被计算的构造函数。在这种情况下,在private之前评估public(仅使用可见性作为标识符)。

相关问题