7

我想使用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已实现,为简洁起见,此处略去。)谢谢!

4

1 回答 1

9

IEnumerator<T>继承自IEnumerator接口。两者都有GetCurrent()方法,一是常用方法,二是泛型T方法;

所以在你的课堂上你必须同时实现它们getCurrent():TObject(from IEnumerator)和getCurrent():T(from 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;
于 2012-08-16T10:07:06.883 回答