[英]Generic implementation of interface
Why isn't this working ? 为什么这不起作用?
public interface IPoint
{
// not important
}
public interface IPointList
{
List<IPoint> Points { get; }
}
public abstract class Point : IPoint
{
// implemented IPoint
}
public abstract class PointList<TPointType> : IPointList
where TPointType: IPoint
{
public abstract List<TPointType> Points { get; } // <- doesn't compile
}
The TPointType obviously has to be an IPoint. TPointType显然必须是IPoint。 Why this implementation is not allowed ?
为什么不允许这种实现?
regards, Kate 问候,凯特
As an answer to your comment, on how to get best of both worlds; 作为对您的评论的回答,有关如何兼顾两方面的问题; I was thinking of something like this, where you implement your interface GetPoints property explictily, create a GetPoints property that is 'more typed', and an protected abstract method that you can override in concrete implementations.
我在想这样的事情,您可以在其中明确实现接口GetPoints属性,创建“类型更多”的GetPoints属性,以及可以在具体实现中覆盖的受保护抽象方法。
The 2 properties call the abstract implementation. 这2个属性称为抽象实现。
public abstract class PointList<T> : IPointList where T : IPoint
{
public IList<T> GetPoints
{
get
{
return GetPointsCore ();
}
}
IList<IPoint> IPointList.GetPoints
{
get
{
return GetPointsCore () as IList<IPoint>;
}
}
protected abstract IList<T> GetPointsCore();
}
The class PointList should implement the IPointList interface. PointList类应实现IPointList接口。 Methods/properties cannot differ by return type only, which is what you're trying to do with the Points declaration in class PointList.
方法/属性不能仅因返回类型而异,这就是您要对PointList类中的Points声明进行的操作。 If you implement
如果实施
List<TPointType> Points { get; }
then logically you cannot implement 那么从逻辑上讲你不能实现
List<IPoint> Points { get; }
Because they would differ by return type only. 因为它们只会因返回类型而不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.