掌握 C# 构造函数重载:灵活创建对象的多种姿势
C# 构造函数重载完全指南
深入掌握 C# 构造函数重载:通过变化参数个数、类型、顺序实现灵活对象初始化,附实战代码示例与设计建议。
C# 中的构造函数重载与方法重载原理一致:一个类可以声明多个同名(即类名)但签名不同的构造函数。编译器根据实例化时提供的实参自动选择匹配的构造函数。
构造函数签名的差异体现在三个维度:
- 参数个数不同
- 参数类型不同
- 参数顺序不同
阅读前建议先了解 C# 基础构造函数 概念。
1. 改变参数个数
最直观的重载方式:提供不同数量参数的构造函数。
class Car {
// 无参构造函数
Car() { ... }
// 单参数构造函数
Car(string brand) { ... }
// 双参数构造函数
Car(string brand, int price) { ... }
}
上述 Car 类三个构造函数共存,因为各自签名唯一。实例化时编译器按实参个数自动匹配。
示例:按参数个数重载
using System;
namespace ConstructorOverload {
class Car {
// 无参构造函数
Car() {
Console.WriteLine("Car 无参构造函数");
}
// 单参数构造函数
Car(string brand) {
Console.WriteLine("Car 单参数构造函数");
Console.WriteLine("品牌: " + brand);
}
static void Main(string[] args) {
// 调用无参构造函数
Car car = new Car();
Console.WriteLine();
// 调用单参数构造函数
Car car2 = new Car("Bugatti");
Console.ReadLine();
}
}
}
输出
Car 无参构造函数 Car 单参数构造函数 品牌: Bugatti
编译器根据传入实参自动选择匹配的构造函数。
2. 改变参数类型
参数个数相同时,通过参数类型差异实现重载。
class Car {
Car(string brand) { ... }
Car(int price) { ... }
}
两个构造函数均接受单个参数,但类型分别为 string 与 int,签名不同。
示例:按参数类型重载
using System;
namespace ConstructorOverload {
class Car {
// string 参数构造函数
Car(string brand) {
Console.WriteLine("品牌: " + brand);
}
// int 参数构造函数
Car(int price) {
Console.WriteLine("价格: " + price);
}
static void Main(string[] args) {
Car car = new Car("Lamborghini");
Console.WriteLine();
Car car2 = new Car(50000);
Console.ReadLine();
}
}
}
输出
品牌: Lamborghini 价格: 50000
3. 改变参数顺序
参数个数、类型均相同但顺序不同,同样构成重载。
class Car {
Car(string brand, int price) { ... }
Car(int speed, string color) { ... }
}
两个构造函数均为 (string, int) 与 (int, string),参数类型序列不同,签名区分度足够。
示例:按参数顺序重载
using System;
namespace ConstructorOverload {
class Car {
// string 先,int 后
Car(string brand, int price) {
Console.WriteLine("品牌: " + brand);
Console.WriteLine("价格: " + price);
}
// int 先,string 后
Car(int speed, string color) {
Console.WriteLine("速度: " + speed + " km/h");
Console.WriteLine("颜色: " + color);
}
static void Main(string[] args) {
Car car = new Car("Bugatti", 50000);
Console.WriteLine();
Car car2 = new Car(60, "Red");
Console.ReadLine();
}
}
}
输出
品牌: Bugatti 价格: 50000 速度: 60 km/h 颜色: Red
进阶技巧:构造函数链调用(this())
为避免代码重复,可在一个构造函数中调用另一个:
class Car {
public string Brand { get; set; }
public int Price { get; set; }
public string Color { get; set; }
// 主构造函数(最完整参数)
public Car(string brand, int price, string color) {
Brand = brand;
Price = price;
Color = color;
}
// 通过 this() 调用主构造函数,提供默认值
public Car(string brand, int price) : this(brand, price, "Black") { }
public Car(string brand) : this(brand, 0, "Black") { }
public Car() : this("Unknown", 0, "Black") { }
}
这种构造函数链模式将初始化逻辑集中在主构造函数中,其他构造函数仅负责提供默认值,极大提升可维护性。
设计建议
- 主构造函数模式:始终提供一个“最完整参数”的主构造函数,其他构造函数通过
this()链式调用它。 - 避免过度重载:超过 3-4 个构造函数时,考虑使用建造者模式或工厂方法替代。
- 只读字段初始化:
readonly字段只能在构造函数中赋值,重载时确保所有路径都正确初始化。 - 参数验证:在主构造函数中集中验证参数合法性,避免重复代码。
C语言