delphigenericsfor-in-loop

Compile error on iterating through self in inherited generic collection


I'm new to Delphi but am experienced in C# an would normally think this is a pretty easy thing to do but am getting a

"E2430 for-in statement cannot operate on collection type 'Class reference'"

in the following code on the line where I'm doing the "for jobActivity in self do". I've just about blown a fuse trying different things here but I've come to nought! I would have thought that there should be some simple way to do this and I'm sure I must be missing something. Can anyone help?

type
  TJobActivityDetailCollection = class(TObjectList<TJobActivityDetail>)
    class function ForYear(year: integer):TJobActivityDetailCollection;
  end;

class function TJobActivityDetailCollection.ForYear(year: integer)
                                      :TJobActivityDetailCollection;
var
  returnCollection   : TJobActivityDetailCollection;
  yearStart, yearEnd : TDateTime;
  jobActivity        : TJobActivityDetail;
begin
  yearStart := EncodeDateTime(year,7,1,0,0,0,0);
  yearEnd   := EncodeDateTime(year + 1,6,30,23,59,59,0);

  returnCollection := TJobActivityDetailCollection.Create();

  for jobActivity in self do
  begin
    if (jobActivity.Date > yearStart) and (jobActivity.Date > yearEnd) then
    begin
      returnCollection.Add(jobActivity);
    end;
  end;

  Result := returnCollection;
end;

Solution

  • Class functions in Delphi are the C# equivalent of static. You can't access self (this) from a "static" method. Just remove class from function.