【发布时间】:2010-12-27 01:04:40
【问题描述】:
我正在为 3D 建模程序编写插件。我有一个自定义类,它包装 3D 模型中的元素实例,然后从它包装的元素中派生它的属性。当模型中的元素发生变化时,我希望我的类根据新几何更新它们的属性。
在下面的简化示例中。我有类 AbsCurveBasd、Extrusion 和 Shell,它们都是相互派生的。这些类中的每一个都实现了一个 RefreshFromBaseShape() 方法,该方法根据类正在包装的当前 baseShape 更新特定属性。
我可以在 RefreshFromBaseShape() 的每个实现中调用 base.RefreshFromBaseShape() 以确保更新所有属性。但我想知道是否有更好的方法让我不必记住在每次RefershFromBaseShape() 的实现中都这样做?例如,因为 AbsCurveBased 没有无参数构造函数,除非构造函数调用基类构造函数,否则代码甚至无法编译。
public abstract class AbsCurveBased
{
internal Curve baseShape;
double Area{get;set;}
public AbsCurveBased(Curve baseShape)
{
this.baseShape = baseShape;
RefreshFromBaseShape();
}
public virtual void RefreshFromBaseShape()
{
//sets the Area property from the baseShape
}
}
public class Extrusion : AbsCurveBased
{
double Volume{get;set;}
double Height{get;set;}
public Extrusion(Curve baseShape):base(baseShape)
{
this.baseShape = baseShape;
RefreshFromBaseShape();
}
public override void RefreshFromBaseShape()
{
base.RefreshFromBaseShape();
//sets the Volume property based on the area and the height
}
}
public class Shell : Extrusion
{
double ShellVolume{get;set;}
double ShellThickness{get;set;}
public Shell(Curve baseShape): base(baseShape)
{
this.baseShape = baseShape;
RefreshFromBaseShape();
}
public void RefreshFromBaseShape()
{
base.RefreshFromBaseShape();
//sets this Shell Volume from the Extrusion properties and ShellThickness property
}
}
【问题讨论】:
标签: c# inheritance methods polymorphism virtual