How to properly make an interface support iteration?

后端 未结 2 1073
逝去的感伤
逝去的感伤 2021-01-06 01:53

How can I expose this TList from an interface, as either IEnumerator or IEnumerator? I am using Delphi XE.

Here\'s h

2条回答
  •  自闭症患者
    2021-01-06 02:17

    Not an answer to your question directly (still working on that), but this is what I did to get an "interfaced enumerator", ie and interfaced class that supports iteration:

    IList = interface(IInterface)
      [...]
      function GetEnumerator: TList.TEnumerator;
      function Add(const Value: T): Integer;
    end;
    
    type
      TBjmInterfacedList = class(TBjmInterfacedObject, IList)
      strict private
        FList: TList;
        function GetEnumerator: TList.TEnumerator;
      strict protected
        function Add(const Value: T): Integer;
      public
        constructor Create; override;
        destructor Destroy; override;
      end;
    
    implementation
    
    constructor TBjmInterfacedList.Create;
    begin
      inherited;
      FList := TList.Create;
    end;
    
    destructor TBjmInterfacedList.Destroy;
    begin
      FreeAndNil(FList);
      inherited;
    end;
    
    function TBjmInterfacedList.GetEnumerator: TList.TEnumerator;
    begin
      Result := FList.GetEnumerator;
    end;
    
    function TBjmInterfacedList.Add(const Value: T): Integer;
    begin
      Result := FList.Add(Value);
    end;
    

    And then you can do stuff like:

    ISite = interface(IInterface)
      ...
    end;
    ISites = interface(IList);
      ...
    end;
    
    var
      for Site in Sites do begin
        ...
      end;
    

    with implementing classes like:

    TSite = class(TBjmInterfacedObject, ISite)
      ...
    end;
    TSites = class(TBjmInterfacedList, ISites)
      ...
    end;
    

    Update

    Example project source uploaded to http://www.bjmsoftware.com/delphistuff/stackoverflow/interfacedlist.zip

提交回复
热议问题