有时,在一个类中有几个构造函数,以容纳某些可选参数,这些构造函数包含一些共同的代码。例如,如下情况:
Class Car
{
private string _description;
private int _nWheels;
public Car(string description,unit nWheels)
{
_description = description;
_nWheels = nWheels;
}
public Car(string description)
{
_description = description;
_nWheels = 4;
}
//etc.
}
这两个构造函数初始化相同的字段,显然,最好把所有的代码放在一个地方。C#有一个特殊的语法,称为构造函数初始化器,可以实现此目的:
Class Car
{
private string _description;
private int _nWheels
public Car(string description , int nWheels)
{
_description = description;
_nWheels = nWheels;
}
public Car(string description) : this(description ,4)
{
}
//