簡體   English   中英

實現通用接口的類

[英]Classes implementing generic interfaces

問題描述

我正在努力讓我的通用接口工作。 我有一個IContainer<TShape>接受形狀列表,其中形狀必須實現IShape<TPoint>接口。 IShape<TPoint>接口有一個點列表,其中的點必須實現IPoint接口。 我正在努力解決的部分是IContainer<TShape>接口上的where約束。

我得到的錯誤是:

類型“TPoint”不能用作泛型類型或方法“IShape”中的類型參數“TPoint”。 沒有從“TPoint”到“Domain.Entities.IPoint”的裝箱轉換或類型參數轉換。 [域名]csharp(CS0314)

接口

容器接口:

public interface IContainer<TShape, TPoint> where TShape : IShape<TPoint>
{
    public Guid Id { get; set; }
    public List<TShape<TPoint>> Shapes { get; set; }
}

形狀界面:

public interface IShape<TPoint> where TPoint : IPoint
{
    public Guid Id { get; set; }
    public List<TPoint> Coordinates { get; set; }
}

點接口:

public interface IPoint
{
    public double X { get; set; }
    public double Y { get; set; }
}

楷模

我希望我的模型工作的方式是:

容器 model:

public class Container : IContainer<Shape, Point>
{
    public Guid Id { get; set; }
    public List<Shape<Point>> Shapes { get; set; }
}

形狀 model:

public class Shape: IShape<Point>
{
    public Guid Id { get; set; }
    public List<Point> Coordinates { get; set; }
}

點model:

public class Point : IPoint
{
    public double X { get; set; }
    public double Y { get; set; }
}

使這項工作需要什么語法?

我認為問題在於,在 IContainer 上,您只為 TShape 提供類型約束,而 IShape 還需要對 TPoint 進行類型約束。

嘗試將您的 IContainer 接口修改為以下內容:

public interface IContainer<TShape, TPoint>
    where TShape : IShape<TPoint>
    where TPoint : IPoint
{
    public Guid Id { get; set; }
    public List<TShape<TPoint>> Shapes { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM