C#泛型接口实现遇CS0314错误,求正确语法解决方案
泛型接口实现错误修复方案
错误提示
The type 'TPoint' cannot be used as type parameter 'TPoint' in the generic type or method 'IShape'. There is no boxing conversion or type parameter conversion from 'TPoint' to 'Domain.Entities.IPoint'. [Domain]csharp(CS0314)
问题根源
IContainer缺少TPoint的约束:仅约束了TShape实现IShape<TPoint>,但未明确TPoint必须实现IPoint,编译器无法推断TPoint满足IShape的泛型要求。Shapes属性类型错误:TShape本身是绑定了特定TPoint的形状实现(而非泛型类型),但代码中错误地将其声明为List<TShape<TPoint>>。
修复步骤
1. 修正IContainer接口定义
补充TPoint的约束,并修正Shapes属性类型:
public interface IContainer<TShape, TPoint> where TShape : IShape<TPoint> where TPoint : IPoint // 新增TPoint的约束 { public Guid Id { get; set; } public List<TShape> Shapes { get; set; } // 修正为List<TShape> }
2. 修正Container模型实现
同步调整Shapes属性的类型:
public class Container : IContainer<Shape, Point> { public Guid Id { get; set; } public List<Shape> Shapes { get; set; } // 修正为List<Shape> }
修复后完整代码
接口定义
public interface IPoint { public double X { get; set; } public double Y { get; set; } } public interface IShape<TPoint> where TPoint : IPoint { public Guid Id { get; set; } public List<TPoint> Coordinates { get; set; } } public interface IContainer<TShape, TPoint> where TShape : IShape<TPoint> where TPoint : IPoint { public Guid Id { get; set; } public List<TShape> Shapes { get; set; } }
模型实现
public class Point : IPoint { public double X { get; set; } public double Y { get; set; } } public class Shape: IShape<Point> { public Guid Id { get; set; } public List<Point> Coordinates { get; set; } } public class Container : IContainer<Shape, Point> { public Guid Id { get; set; } public List<Shape> Shapes { get; set; } }
内容的提问来源于stack exchange,提问作者zwoolli
相关产品推荐
相关产品推荐

