先构造基类,再完成派生对象
修改输入并运行构造链;随后用模式匹配观察何时能安全访问派生类成员。
对象初始化模拟器
1进入
Shipment(...),校验共性状态2基类只读属性初始化完成
3进入具体派生构造函数
等待运行…
构造函数不是虚成员,也不会被继承;派生构造函数用 base(...) 选择基类构造函数。
对应 C#
public abstract class Shipment
{
protected Shipment(string id, decimal kg)
{
TrackingId = string.IsNullOrWhiteSpace(id)
? throw new ArgumentException()
: id;
WeightKg = kg > 0
? kg
: throw new ArgumentOutOfRangeException();
}
public string TrackingId { get; }
public decimal WeightKg { get; }
}
public sealed class FragileShipment : Shipment
{
public FragileShipment(string id, decimal kg, int risk)
: base(id, kg)
{
RiskLevel = risk is >= 1 and <= 5
? risk
: throw new ArgumentOutOfRangeException();
}
public int RiskLevel { get; }
}
if (shipment is FragileShipment { RiskLevel: >= 4 } fragile)
Console.WriteLine($"Escalate {fragile.TrackingId}");