如何在“组件”类中添加受保护的虚拟方法,以便可以从“复合”中调用它?
作为一个具体的例子,看看下面的代码,请告诉我如何避免DxCompositeShape.ComputeSize
.
abstract class DxShape // this is the Component
{
public abstract void Paint();
protected abstract void ComputeSize();
}
class DxCompositeShape : DxShape // this is the Composite
{
public readonly IList<DxShape> Shapes = new List<DxShape>();
public override void Paint()
{
this.ComputeSize();
}
protected override void ComputeSize()
{
foreach (DxShape sh in Shapes)
{
sh.ComputeSize(); // compiler error CS1540
}
// and some other logic here
}
}
编辑:我修改了我的示例,所以我没有(人们认为 Init 总是可以在构造函数中调用)ComputeSize
。Init