【问题标题】:Classes implementing generic interfaces实现通用接口的类
【发布时间】:2022-11-18 06:13:05
【问题描述】:

问题描述

我正在努力让我的通用接口工作。我有一个带有形状列表的 IContainer<TShape>,其中形状必须实现 IShape<TPoint> 接口。 IShape<TPoint>接口有一个点列表,其中的点必须实现IPoint接口。我正在努力解决的部分是 IContainer<TShape> 接口上的 where 约束。

我得到的错误是:

类型“TPoint”不能用作类型参数“TPoint” 泛型类型或方法“IShape”。没有拳击转换 或类型参数从 'TPoint' 转换为 '域.实体.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; }
}

楷模

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

集装箱型号:

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

外形型号:

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

点模型:

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

使这项工作需要什么语法?

【问题讨论】:

    标签: c#


    【解决方案1】:

    我认为问题在于,在 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; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多