I am trying to expose the build in TEnumerator for a private static array.
Delphi itself allows to enumerate a static array directly (see below) so I suspect that Delphi creates an enumerator in the background for the static array and I am hoping that I will be able to create and expose the same enumerator in GetEnumerator method.
(I am using Delphi XE2).
program Project6;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections;
type
TMyEnum = (meA, meB);
TMyClass = class
private
FItems: array[TMyEnum] of Integer;
protected
public
function GetEnumerator: TEnumerator<Integer>;
end;
{ TMyClass }
function TMyClass.GetEnumerator: TEnumerator<Integer>;
begin
// What is the simplies way of creating this enumerator?
end;
var
myObj: TMyClass;
i: Integer;
begin
myObj := TMyClass.Create;
try
// This works but only in the same unit
for i in myObj.FItems do
WriteLn(i);
for i in myObj do
WriteLn(i);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
ReadLn;
end.
Note that I can write a custom emulator like below. But I am trying to avoid this and expose the built in one.
TStaticArrayEnumerator<T> = class(TEnumerator<T>)
private
FCurrent: Pointer;
FElementAfterLast: Pointer;
protected
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(aArray: Pointer; aCount: Integer);
end;
{ TStaticArrayEnumerator<T> }
constructor TStaticArrayEnumerator<T>.Create(aArray: Pointer; aCount: Integer);
begin
// need to point Current before the first element (see comment in DoMoveNext)
FCurrent := Pointer(NativeInt(aArray) - SizeOf(T));
FElementSize := aElementSize;
FElementAfterLast := Pointer(NativeInt(aArray) + aCount * SizeOf(T))
end;
function TStaticArrayEnumerator<T>.DoGetCurrent: T;
begin
Result := T(FCurrent^);
end;
function TStaticArrayEnumerator<T>.DoMoveNext: Boolean;
begin
// This method gets called before DoGetCurrent gets called the first time
FCurrent := Pointer(NativeInt(FCurrent) + SizeOf(T));
Result := not (FCurrent = FElementAfterLast);
end;
You cannot. There is no type that represents the enumerator for an array. When you write a for..in loop over the elements of an array, the compiler deals with that by inlining a classic for loop.
Consider this program:
And the code that is generated:
Frankly, the best you can do is very similar to what you already have. The problem with what you already have is the heap allocation. Write your enumerator using a record rather than a class, like this:
And then your
GetEnumerator
is implemented like so: