【问题标题】:Calling a method on a List of Generic Type from abstract Parent class从抽象父类调用通用类型列表上的方法
【发布时间】: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&lt;T&gt; Shift&lt;T&gt;(Shift inShift) where T : IEdge
  • 我假设IEdge 有一个Shift 方法,您应该调用PlanBoundaries 中的每个项目而不是列表本身。如果是这样,@YuvalItzchakov 关于如何处理它是正确的,这样您就不需要在 PolygonNonPolygon 类中覆盖 Shift

标签: c# generics inheritance polymorphism


【解决方案1】:

您可以缩小 PlaneRegion 类的范围,只允许在 T 中实现 IEdge 接口:

public abstract class PlaneRegion<T> where T : IEdge
{
    public abstract List<T> PlaneBoundaries { get; set; }
}

此外,在Shift 函数中,您可能希望将其应用于列表中的每个项目,而不是整个列表,因此您应该将其更改为:

//In PlaneRegion
public PlaneRegion<T> Shift(Shift inShift)
{
    this.PlaneBoundaries.ForEach(x => x.Shift(passedShift)); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2013-09-17
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多