Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从同一类中的其他构造函数调用构造函数_C#_Constructor - Fatal编程技术网

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

C# 从同一类中的其他构造函数调用构造函数,c#,constructor,C#,Constructor,我有一个有两个构造函数的类: public class Lens { public Lens(string parameter1) { //blabla } public Lens(string parameter1, string parameter2) { // want to call constructor with 1 param here.. } } 我想从第二个构造函数调用第一个构造函数。这在C#中可

我有一个有两个构造函数的类:

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

    public Lens(string parameter1, string parameter2)
    {
       // want to call constructor with 1 param here..
    }
}
我想从第二个构造函数调用第一个构造函数。这在C#中可能吗?

追加
:此(必需参数)
在构造函数末尾执行的“构造函数链接”

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

来源

是的,您将使用以下

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

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

    }
}

链接施工人员时,还必须考虑施工人员评估的顺序:

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

    public Lens(string parameter1, string parameter2)
    {
       // want to call constructor with 1 param here..
    }
}
借用Gishu的回答,有一点(为了保持代码的相似性):

如果我们稍微更改在
私有
构造函数中执行的评估,我们将看到为什么构造函数排序很重要:

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
似乎有一个值——它是在调用构造函数中设置的;但是,重要的是要记住构造函数是函数


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

我认为在第二个构造函数中会发生的是,您将创建一个Lens的本地实例,该实例在构造函数末尾超出范围,并且没有分配给“this”。你需要在Gishu的帖子中使用构造器链接语法来实现问题的要求。是的,很抱歉。现在更正。