通用类型父级列表,不接受类型为父列表类型子类型的子级

时间:2014-10-02 14:16:20

标签: c# generics inheritance interface geometry-class-library

这是我目前的班级图:

enter image description here

正如您所看到的,PolygonNonPolygon都是PlaneRegionLineSegment实现IEdge的类型。PlaneRegion是Generic所以我们可以为PlaneBoundaries制作IEdgeNonPolygon的列表,以便它可以LineSegmentarc,或者只有LineSegment Polygon } public class PlaneRegion<T> : Plane, where T : IEdge { public virtual List<T> PlaneBoundaries { get; set; } } public class Polygon : PlaneRegion<LineSegment> { #region Fields and Properties 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; } 。下面是类的示例,以显示它是如何实现的:

PlaneRegion<IEdge>

这一切都运行正常,但当我尝试列出Polygon时,尽管PolygonPlaneRegion<LineSegment>,我仍然不会在列表中添加LineSegment个对象}和IEdge实现List<PlaneRegion<IEdge>> planes = new List<PlaneRegion<IEdge>>(); Polygon polygon1 = new Polygon(); NonPolygon nonPolygon1 = new NonPolygon(); planes.Add(polygon1); //says that .Add() has some invalid arguments planes.Add(nonPolygon1); 。这是给出编译时错误的代码示例:

polygon1

有没有办法将polygon1添加到此类型安全的列表中?我尝试将PlaneRegion<IEdge>转换为(PlaneRegion<IEdge>)(object)类型,但是它产生了一个编译错误,它无法转换类型。我知道我可以做{{1}}但它似乎草率和不安全所以似乎应该有更好的方法。

1 个答案:

答案 0 :(得分:0)

试试这个,它适用于我:

public class Polygon : PlaneRegion<IEdge> 
{
    public new List<LineSegment> PlaneBoundaries
    {
        get { return (_planeBoundaries); }
        set { _planeBoundaries = value; }
    }
    protected List<LineSegment> _planeBoundaries;
}
相关问题