这是我当前的类型层次结构:
我正在尝试实现一种方法PlaneRegion
这将调用一个名为的方法Shift()
在其派生类的列表上,其中该列表在所有列表中都称为 PlaneBoundaries,但它们具有不同的类型
like so:
public abstract class PlaneRegion<T>
{
public abstract List<T> PlaneBoundaries { get; set; }
}
public class Polygon : PlaneRegion<LineSegment>
{
public override List<LineSegment> PlaneBoundaries
{
get { return _planeBoundaries; }
set { _planeBoundaries = value; }
}
protected List<LineSegment> _planeBoundaries;
}
public class NonPolygon : PlaneRegion<IEdge>
{
public override List<IEdge> PlaneBoundaries
{
get { return _planeBoundaries; }
set { _planeBoundaries = value; }
}
private List<IEdge> _planeBoundaries;
}
理想情况下,它还应该返回对象的副本作为其子类,并且不修改原始对象。
目前,我有两个类实现的接口 IEdge:LineSegment 和 Arc。我对抽象超类 PlaneRegion 使用泛型,因为两个继承类 Polygons 和 NonPolygon 都有planeBoundaries,但 Polygon 只包含直线(lineSegments),而 NonPolygon 可以有直线或曲线(LineSegment 或 Arc),所以我实现就像这个问题一样,您可以在下面的片段中看到:使用派生类型和同名覆盖属性 C# https://stackoverflow.com/questions/3551012/override-a-property-with-a-derived-type-and-same-name-c-sharp
但是,由于 PlaneRegion 中的 PlaneRegion 和 PlaneBoundaries 是通用类型,因此当我尝试在 PlaneBoundaries 上调用 shift 时会出现问题。以下是 Shift 当前实施方式的示例:
//In PlaneRegion
public PlaneRegion<T> Shift(Shift inShift)
{
//does not work because Shift isn't defined for type T
this.PlaneBoundaries.Shift(passedShift);
}
//in Polygon
public override Polygon Shift(Shift passedShift)
{
return new Polygon(this.PlaneBoundaries.Shift(passedShift));
}
//In NonPolygon
public override NonPolygon Shift(Shift passedShift)
{
return new NonPolygon(this.PlaneBoundaries.Shift(passedShift));
}
有没有办法像这样在通用列表上调用shift或将T的可能性限制为在编译时实现IEdge的类?我也尝试过将 PlaneRegion 中的 Shift 设为通用,但它也不起作用。
另外,理想情况下,我希望它返回原始对象的副本作为子对象,并修改这些对象的 PlaneBoundaries 而不是原始对象的 PlaneBoundaries,但不知道如何执行此操作。