这是我目前的班级图:
正如您所看到的,Polygon
和NonPolygon
都是PlaneRegion
和LineSegment
实现IEdge
的类型。PlaneRegion
是Generic所以我们可以为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;
}
。下面是类的示例,以显示它是如何实现的:
PlaneRegion<IEdge>
这一切都运行正常,但当我尝试列出Polygon
时,尽管Polygon
为PlaneRegion<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}}但它似乎草率和不安全所以似乎应该有更好的方法。
答案 0 :(得分:0)
试试这个,它适用于我:
public class Polygon : PlaneRegion<IEdge>
{
public new List<LineSegment> PlaneBoundaries
{
get { return (_planeBoundaries); }
set { _planeBoundaries = value; }
}
protected List<LineSegment> _planeBoundaries;
}