• 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.
     
  • 相关阅读:
    FileUpload1上传控件
    docker如何push镜像到docker hub个人的仓库
    docker的ubuntu镜像无ifconfig和ping命令
    keystone同步数据库的时候提示error
    openstack安装dashboard后访问horizon出错 500 or 504
    装了ubuntu之后,只能进入ubuntu系统,不能进入windows系统
    Kernal Panic
    无法获得锁 /var/lib/dpkg/lock -open
    用户 'NT AUTHORITYIUSR' 登录失败
    配置错误:不能在此路径中使用此配置节。
  • 原文地址:https://www.cnblogs.com/pavkoo/p/3557091.html
Copyright © 2020-2023  润新知