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

152

我有一个包含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个回答

231

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

的内容。


34

是的,你需要使用以下内容

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

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

    }
}

我认为在第二个构造函数中会发生的情况是,您将创建一个局部的Lens实例,该实例在构造函数结束时超出范围,并且未分配给"this"。 您需要使用Gishu帖子中的构造函数链接语法来实现问题所要求的内容。 - Colin Desmond
是的,对此感到抱歉。现已更正。 - Matthew Dresser

15
构造函数的评估顺序在链接构造函数时也必须考虑:
借用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构造函数体之前“返回”。换句话说,最后一个被调用的构造函数是第一个被评估的构造函数。在这种情况下,privatepublic之前被评估(只是使用可见性作为标识符)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接