根据我所学到的,如果经常在类层次结构中使用向下转换,那就不好了.我同意这一点,但是如果有的话,这个规则有什么例外?
这就是我的图形编辑器设计显得很薄的地方:我有两个层次结构,其中几何图形层次结构与图形基元分离.像这样:
public class GeometricPrimitive {...}
public class RectangeGeometric: Geometric Primitive {...}
public class GraphicPrimitive {...}
public class Rectangle: GraphicPrimitive {
private RectangleGeometric figure;
...
}
Run Code Online (Sandbox Code Playgroud)
因此,每个具体的图形图类都封装了具体几何类的实例.
这种方法是正确的,还是我更喜欢更通用的方法? - 不幸的是,在这种情况下会使用向下转换:
public class GraphicPrimitive {
protected GeometryPrimitive figure;
....
}
public class Rectangle: GraohicPrimitive {
public Rectangle(Color c, TwoDPoint leftHighPoint, TwoDPoint rightLowPoint):
base(new RectangleGeometric(leftHighPoint.Point2D, rightLowPoint.Point2D), c) { }
#region Geometric Properties
public TwoDPoint LeftTopCorner {
get { return new TwoDPoint(base.color, (base.figure as RectangleGeometric).LeftTopCorner); }
}
public TwoDPoint RightBottomCorner {
get { …Run Code Online (Sandbox Code Playgroud) oop ×1