【发布时间】:2014-09-30 18:51:09
【问题描述】:
这是我当前的类型层次结构:
我正在尝试在PlaneRegion 中实现一个方法,该方法将在其派生类的列表中调用名为Shift() 的方法,其中该列表在所有派生类中都称为PlaneBoundaries,但它们属于不同类型
像这样:
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)所以我实现了就像在这个问题中一样,您可以在下面的 sn-ps 中看到:Override a Property with a Derived Type and Same Name C#
但是,因为 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,但不这样做。
【问题讨论】:
-
你试过限制泛型方法吗?
public PlaneRegion<T> Shift<T>(Shift inShift) where T : IEdge -
我假设
IEdge有一个Shift方法,您应该调用PlanBoundaries中的每个项目而不是列表本身。如果是这样,@YuvalItzchakov 关于如何处理它是正确的,这样您就不需要在Polygon和NonPolygon类中覆盖Shift。
标签: c# generics inheritance polymorphism