这是我当前的类图:
如您所见,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;
}
一切正常,但是当我尝试列出 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)
但它看起来草率且不安全,所以似乎应该有更好的方法。
最佳答案
试试这个,对我来说效果很好:
public class Polygon : PlaneRegion<IEdge>
{
public new List<LineSegment> PlaneBoundaries
{
get { return (_planeBoundaries); }
set { _planeBoundaries = value; }
}
protected List<LineSegment> _planeBoundaries;
}
关于c# - 通用类型父列表不接受子类型是父列表类型的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162825/