DELPHI 里面的迭代

迭代(Iiterator)的作用:遍历一个集合(Collections)的每一个元素(item)。

delphi 2005之后新加入一种 for .. in .. 遍历语句,支持String,Set,array,record,Interface,class。能够时代码的for循环更加简洁。

以前的结构
var
  S: string;
  i: integer;
begin
  for i := 0 to MyStrings.Count-1 do
  begin
    S := MyStrings[i];
    writeln(S);
  end;
end;
 
现在的结构
var
  S: string;
begin
  for S in MyStrings do
    writeln(S);
end;
为了自定义这种结构,我们的代码需要满足如下规则:
1.你必须有一个 class , interface 或者 record 的自定义类型
2.你的 class ,interface 或者record类型必须暴露一个GetEnumerator方法,该方法返回一个你的迭代器
3.你的迭代器可以是class , interface 或者 record中的一种类型。
4.你的迭代器需要暴露MoveNext(): boolean; Current:你的元素类型。
5.MoveNext方法在当前选中的元素是最后一个之后返回False,否则返回True
6.你的迭代器创建之时当前元素应该为-1,在调用moveNext之后才能指向第一个元素。
 
如下例:
 
type
  { 迭代器 }
  TRecordEnumerator = record
  private
    FArray: TBytes;
    FIndex: Integer;

    function GetCurrent: Byte;
  public
    function MoveNext(): Boolean;
    property Current: Byte read GetCurrent;
  end;

  { 需要被迭代的集合}
  TRecordCollection = record
  private
    FArray: TBytes;
  public
    function GetEnumerator(): TRecordEnumerator;
  end;

{ TRecordCollection }

function TRecordCollection.GetEnumerator: TRecordEnumerator;
begin
  Result.FArray := FArray;
  Result.FIndex := -1;
end;

{ TRecordEnumerator }

function TRecordEnumerator.GetCurrent: Byte;
begin
  Result := FArray[FIndex];
end;

function TRecordEnumerator.MoveNext: Boolean;
begin
  Inc(FIndex);

  if FIndex >= Length(FArray) then
    Exit(false);

  Exit(true);
end;

var
  LColl: TRecordCollection;
  B: Byte;

begin
  LColl.FArray := TBytes.Create(1, 2, 3, 4, 5, 6);

  for B in LColl do
    WriteLn(B);

  ReadLn;
end.
 
原文地址:https://www.cnblogs.com/pavkoo/p/3557091.html