c# - 通用类型父列表不接受子类型是父列表类型的子类型

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

这是我当前的类图:

enter image description here

如您所见,PolygonNonPolygonPlaneRegion 的类型和 LineSegment工具 IEdge .PlaneRegion是通用的,所以我们可以列出它的 PlaneBoundaries IEdge对于 NonPolygon所以它可以有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尽管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/

相关文章:

c# - 确保泛型方法中的参数基于同一类中的参数

c# - 如何重构这些泛型方法?

java - super 在下面的代码中是如何工作的? ( java )

arrays - 是否可以在 Swift 中将子类型的元组添加到类型的元组数组中?

python - 在python中将属性添加到int值

c# - 将 id 标识值存储在变量中

c# - 检查 foreach 中的最后一个元素

c# - Enumerable.First (System.Linq) C# 的替代方案

json - ContextualDeserializer,用于使用 Jackson 将 JSON 映射到不同类型的映射

swift - 协议(protocol)不符合自身?