实现接口返回的类是否可以是自己的类型



我使用的是.NET CORE 7预览版,我创建了一个非常基本的界面:

public interface IRegularPolygon
{
static readonly int SideCount;
public RectangleF Bounds { get; }
public IList<PointF> Points { get; }
public static abstract IRegularPolygon Create(Point location, int radius);
public static abstract Point GetCentroid(PointF[] points);
}

我在几个类中实现了它。E.G:

class Hexagon : IRegularPolygon
{
// Working
public static IRegularPolygon Create(Point location, int radius)
{
// Creating the Hexagon
}
// Working too, but I would like to avoid casting
public static IRegularPolygon Create(Point location, int radius)
{
// Creating the Hexagon
return (Hexagon)hexagon;  // still need to cast (Hexagon) when calling this method
}
// What I want to achieve.
// [ERROR] Don't implement IRegularPolygon
public static Hexagon Create(Point location, int radius)
{
// Creating the Hexagon;
return hexagon // as Hexagon type
}
}

所以,它正在发挥作用。我可以使用var hexagon = (Hexagon)Hexgon.Create();

我确实理解方法public static Hexagon Create(Point location, int radius)中的编译错误。

我希望既然实现了接口,就可以返回类型本身(该示例中为Hexagon(。

这有可能实现吗?还是我应该去继承遗产?

谢谢你的回答!

Aurélien。

定义接口的原因是为了让调用方知道要发生什么。对于调用者来说,返回IRegularPolygon的什么实现应该无关紧要。如果将Hexagon铸造为IRegularPolygon,则可以返回Hexagon。

然而,如果您只是想强制执行一个模式,其中每个类都有一个Create方法,那么接口就不是您所需要的。也许抽象基类会更好地为您服务:

public abstract class RegularPolygon
{
public static RegularPolygon Create(Point location, int radius) 
{
throw new NotImplementedExecption();
}
}
public class Hexagon : RegularPolygon
{
public static new Hexagon Create(Point location, int radius)
{
//implement method
}
}

最新更新