这是我当前的类图:

如您所见,Polygon和NonPolygon都是PlaneRegion和LineSegment实现的类型IEdge。这PlaneRegion是通用的,所以我们可以列出它的一个列表,PlaneBoundaries以便IEdge它NonPolygon可以具有LineSegment或arc,或者它们只能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;
}
这一切都很好,但是当我尝试制作它的列表时,尽管是 a和implemting ,但我PlaneRegion<IEdge>不会将对象添加到列表中。这是给我一个编译时错误的代码示例:PolygonPolygonPlaneRegion<LineSegment>LineSegmentIEdge
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),但它似乎草率且不安全,因此似乎应该有更好的方法。