是否有attribute
或pattern
告诉编译器不允许覆盖可重写方法?
例如:
Vehicle
public class Vehicle
{
public virtual void Start() { }
}
Car
public class Car : Vehicle
{
// ################
[DontAllowOverrideAgain] //I need something like this attribute
// ################
public override void Start()
{
// Todo => codes that every car must invoke before start ...
CarStart();
// Todo => codes that every car must invoke after start ...
}
public virtual void CarStart() { }
}
CoupeCar
public class CoupeCar : Car
{
// throw and error or show a message to developer
public override void Start() { }
public override void CarStart() { }
}
答案 0 :(得分:5)
当然,只需将第一个替代项创建为sealed
,这将导致开发人员可以看到的编译时失败
public class Car : Vehicle
{
public sealed override void Start()
{
// Todo => codes that every car must invoke before start ...
CarStart();
// Todo => codes that every car must invoke after start ...
}
public virtual void CarStart() { }
}
答案 1 :(得分:1)
在这里,使用密封
参考https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed
public class Car : Vehicle
{
sealed protected override void Start()
{
// Todo => codes that every car must invoke before start ...
CarStart();
// Todo => codes that every car must invoke after start ...
}
public virtual void CarStart() { }
}