Llamar al constructor desde otro constructor en la misma clase


Tengo una clase con 2 constructores:

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

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

Quiero llamar al primer constructor desde el segundo. Es esto posible en C#?

Author: ShuggyCoUk, 2009-05-06

3 answers

Añadir :this(required params) al final del constructor para hacer 'encadenamiento del constructor'

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

Fuente Cortesía de csharp411.com

 203
Author: Gishu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 13:40:40

Sí, usarías lo siguiente

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

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

    }
}
 31
Author: Matthew Dresser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-06 14:28:55

El orden de evaluación del constructor también debe tenerse en cuenta al encadenar constructores:

Para tomar prestado de la respuesta de Gishu, un poco (para mantener el código algo similar):

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

Si cambiamos ligeramente la evaluación realizada en el constructor private, veremos por qué el orden del constructor es importante:

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

Arriba, he agregado una llamada a función falsa que determina si property C tiene un valor. A primera vista, podría parecer que C tienen un valor, como se establece en el llamado constructor; sin embargo, es importante recordar que los constructores son funciones.

this(a, b) se llama - y debe "devolver" - antes de que se realice el cuerpo del constructor public. Dicho de otra manera, el último constructor llamado es el primer constructor evaluado. En este caso, private se evalúa antes de public (solo para usar la visibilidad como identificador).

 10
Author: Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-27 21:08:20