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

Rob*_*Dam 135 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..
    }
}
Run Code Online (Sandbox Code Playgroud)

我想从第二个调用第一个构造函数.这可能在C#中吗?

Gis*_*shu 214

: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;
}
Run Code Online (Sandbox Code Playgroud)

来源csharp411.com


Mat*_*ser 31

是的,您将使用以下内容

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)


Tho*_*mas 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;
}
Run Code Online (Sandbox Code Playgroud)

如果我们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;
}
Run Code Online (Sandbox Code Playgroud)

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

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