A list of a typical typed parent not accepting a child with a type that is a subtype of the parent list type

Here is my diagram of the current class:

enter image description here

As you can see, both Polygon

and NonPolygon

are the types PlaneRegion

and LineSegment

implement IEdge

. PlaneRegion

is generic, so we can make a list of it PlaneBoundaries

either IEdge

for NonPolygon

, so that it can have LineSegment

or arc

, or so that they can only be LineSegment

for Polygon

. Below are examples of classes to show how they are implemented:

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;
}

      

This all works fine, but when I try to make a list PlaneRegion<IEdge>

, it does not allow me to add an item Polygon

to the list, despite the fact that Polygon

is PlaneRegion<LineSegment>

and LineSegment

implemting IEdge

. This is a sample code that gives me a compile time error:

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);

      

Is there a way to add polygon1

to this list that is type safe? I tried casting polygon1

to type PlaneRegion<IEdge>

, but it gave a compile error that cannot convert types. I know I can do it (PlaneRegion<IEdge>)(object)

, but it seems sloppy and unsafe, so it seems like there must be a better way.

+3


source to share


1 answer


Try this, it works great for me:



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

      

0


source







All Articles