构造函数链式调用#
来源:
D:\study\C#1\stu0725\题目三:构造函数的链式调用(进阶技巧)
构造函数链式调用通过 this() 关键字实现:一个构造函数调用同一类中的另一个构造函数,形成链式传递,减少代码重复。
示例:Car → ElectricCar#
class Car
{
public readonly string Brand;
public string Model { get; set; }
public string Color { get; set; }
// 最完整的构造函数(3 个参数)
public Car(string brand, string model, string color)
{
Brand = brand;
Model = model;
Color = color;
}
// 链式调用:只传 brand 和 model,color 默认"白色"
public Car(string brand, string model) : this(brand, model, "白色")
{
}
// 无参构造函数(什么参数都不传)
public Car() { }
public void CarInfo()
{
Console.WriteLine($"品牌:{Brand}\n车型:{Model}\n颜色:{Color}");
}
}
class ElectricCar : Car
{
public int BatterySize { get; set; }
public ElectricCar(int batterySize, string brand, string model) : base(brand, model)
{
BatterySize = batterySize;
}
public void CarInfo()
{
base.CarInfo(); // 调用父类的 CarInfo
Console.WriteLine($"电池容量:{BatterySize}kWh");
}
}
运行示例:
Car car = new Car("宝马", "X5", "黑色");
car.CarInfo();
// 输出:品牌:宝马 / 车型:X5 / 颜色:黑色
ElectricCar electricCar = new ElectricCar(80, "天堂", "上帝");
electricCar.CarInfo();
// 输出:品牌:天堂 / 车型:上帝 / 颜色:白色(默认值)
// 电池容量:80kWh
链式调用规则#
| 规则 | 说明 |
|---|---|
this() 必须放在构造函数体的第一行 |
编译器需要先确定调用哪个构造函数 |
| 不能形成循环调用 | A→B→A 会导致编译错误 |
this() 和 base() 不能同时使用 |
只能选择一种链式方向 |