在C#构造函数头中使用冒号

ank*_*311 15 c# constructor

下面是一个struct名为Complex 的构造函数,它有两个成员变量,Real和Imaginary:

public Complex(double real, double imaginary) : this()
{
 Real = real;
 Imaginary = imaginary;
}
Run Code Online (Sandbox Code Playgroud)

函数头中冒号后的部分有什么用?

Pra*_*ana 22

您始终可以从另一个构建函数中调用一个构造函数.比方说,例如:

public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age) 
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}
Run Code Online (Sandbox Code Playgroud)

this指的是同一个类,所以当我们说this(10),我们实际上是指执行该public mySampleClass(int Age)方法.上述调用方法的方法称为初始化程序.在方法中,我们可以以这种方式使用最多一个初始化器.

在你的情况下,它将调用默认构造函数,没有任何参数


Bri*_*dge 17

这就是所谓的构造函数链-在它其实调用另一个构造函数(它没有任何PARAMS在这种情况下),然后再回来,不会在此构造任何额外的工作(在这种情况下设置的值RealImaginary).

  • 实际上,在设置值之前调用默认构造函数. (4认同)

Ser*_*kiy 8

这是一个构造函数初始化程序,它在构造函数体之前立即调用另一个实例构造函数.有两种形式的构造函数初始值设定项:thisbase.

base 构造函数初始化程序导致调用直接基类的实例构造函数.

this构造函数初始化程序导致调用类本身的实例构造函数.当构造函数初始值设定项没有参数时,则调用无参数构造函数.

class Complex
{
   public Complex() // this constructor will be invoked
   {    
   }

   public Complex(double real, double imaginary) : this()
   {
      Real = real;
      Imaginary = imaginary;
   }
}
Run Code Online (Sandbox Code Playgroud)

BTW通常构造函数链接是从具有较少参数计数的构造函数到具有更多参数的构造函数(通过提供默认值)完成的:

class Complex
{
   public Complex() : this(0, 0)
   {    
   }

   public Complex(double real, double imaginary)
   {
      Real = real;
      Imaginary = imaginary;
   }
}
Run Code Online (Sandbox Code Playgroud)