繁体   English   中英

接口的通用实现

[英]Generic implementation of interface

为什么这不起作用?

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
}

TPointType显然必须是IPoint。 为什么不允许这种实现?

问候,凯特

作为对您的评论的回答,有关如何兼顾两方面的问题; 我在想这样的事情,您可以在其中明确实现接口GetPoints属性,创建“类型更多”的GetPoints属性,以及可以在具体实现中覆盖的受保护抽象方法。
这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();        
    }

PointList类实现IPointList接口。 方法/属性不能仅因返回类型而异,这就是您要对PointList类中的Points声明进行的操作。 如果实施

List<TPointType> Points { get; } 

那么从逻辑上讲你不能实现

List<IPoint> Points { get; }

因为它们只会因返回类型而不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM