多态
本页说明何时让同一调用按对象的实际类型执行不同实现。当前 SCL 的运行时多态合同是接口引用。virtual / override / abstract 用于编译期校验和派生类必须实现的合同,不能当作基类变量上的虚表派发。
接口引用派发
interface IActuator
{
void Actuate();
}
class Valve : IActuator
{
public int ActionCode;
public void Actuate()
{
ActionCode = 10;
}
}
class Cylinder : IActuator
{
public int ActionCode;
public void Actuate()
{
ActionCode = 20;
}
}
IActuator first = new Valve();
IActuator second = new Cylinder();
first.Actuate();
second.Actuate();
同一接口引用可以改绑到另一个实现,后续调用走新的实现:
IActuator actuator = new Valve();
actuator.Actuate();
actuator = new Cylinder();
actuator.Actuate();
抽象方法
基类无法给出默认实现时,用 abstract 强制派生类提供方法。调用时使用派生类的具体类型,或把该方法提升到接口。
public abstract class Sensor
{
public abstract int ReadRaw();
}
public class PressureSensor : Sensor
{
public int RawValue;
public override int ReadRaw()
{
return RawValue;
}
}
PressureSensor sensor = new PressureSensor();
sensor.RawValue = 12;
int raw = sensor.ReadRaw();
is 类型测试
IActuator actuator = new Valve();
bool isValve = actuator is Valve;
需要类型专用行为时,优先把该行为放到接口方法里,不要依赖运行时转换。
扫描循环
固定数量的设备按接口顺序调用。不要为多态引入动态集合。
class ScanLoop
{
public void RunCycle(IActuator first, IActuator second)
{
first.Actuate();
second.Actuate();
}
}
当前支持边界
| 能力 | 状态 |
|---|---|
| 接口引用上的方法派发 | 支持 |
| 同一接口引用改绑后再次调用 | 支持 |
abstract 必须被非抽象派生类实现 | 支持 |
is Type | 支持 |
基类类型变量上的 virtual 运行时派发 | 当前不可用 |
new 隐藏方法 | 当前不可用 |
普通方法中的 base.Method() | 当前不可用 |
as、模式变量、动态集合 | 当前不可用 |
当前不可用
- 把
Motor m = new ServoMotor(); m.Start();当作虚表多态; - 方法隐藏、
as、模式变量; List<T>或按运行时数量枚举设备;- 依赖异常或反射选择实现。