Delphi:为什么抱怨缺少方法实现?

前端之家收集整理的这篇文章主要介绍了Delphi:为什么抱怨缺少方法实现?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用IEnumerator< T>而不是IEnumerator我正在建立的列表.我尝试了以下内容
IMyList = interface(IEnumerator<TElement>)
  procedure Add(Element: TElement);
end;

TMyList = class(TInterfacedObject,IMyList )
private
  function GetCurrent: TElement;
  function MoveNext: Boolean;
  procedure Reset;
public
  property Current: TElement read GetCurrent;
  procedure Add(Element: TElement);
end;

但令我惊讶的是,我被告知TMyList没有实现GetCurrent.为什么编译器告诉我GetCurrent丢失的时候显然没有? (为了记录,GetCurrent已实现,为简洁起见,此处仅省略.)谢谢!

解决方法

的IEnumerator< T>继承自IEnumerator接口.它们都有GetCurrent()方法,其中一种是通常的方法,第二种是泛型T方法;

所以在你的类中你必须实现它们getCurrent():TObject(来自IEnumerator)和getCurrent():T(来自IEnumerator< T>);

一个小问题是两个方法都有相同的参数,你不能简单地声明它们.所以你应该使用别名:

function getCurrentItem() : TElement; //actual method for IEnumerator<T>
  function GetCurrent():TObject;  //method for IEnumerator
  function IMyList.GetCurrent = getCurrentItem; //alias

请参阅docwiki http://docwiki.embarcadero.com/RADStudio/en/Implementing_Interfaces上的Method Resolution Clause

所以,在你的情况下,代码应该看起来像(我标记所有方法摘要):

TElement = class(TObject)
end;

IMyList = interface(IEnumerator<TElement>)
  procedure Add(Element: TElement);
end;

TMyList = class(TInterfacedObject,IMyList )
private
  function getCurrentItem() : TElement; virtual; abstract;

  function IMyList.GetCurrent = getCurrentItem;
  function GetCurrent():TObject;  virtual; abstract;

  function MoveNext(): Boolean;   virtual; abstract;
  procedure Reset(); virtual; abstract;
public
  property Current: TElement read GetCurrentItem;
  procedure Add(Element: TElement); virtual; abstract;
end;
原文链接:https://www.f2er.com/delphi/101164.html

猜你在找的Delphi相关文章