Delphi custom enumerator gives strange errors
-
27-10-2019 - |
Pergunta
When creating a custom enumerator for string parsing I see some strange error messages. When using record It gives the following error:
E2010 Incompatible types: 'TSplitStringEnumerator' and 'Pointer'
When using classes (insert a few .Create calls in the code) instead of records I get some Internal Errors from time to time:
Does anyone know how to keep the enumeration work with record data types instead of classes?
type
TSplitStringEnumerator = record
StringToParse: string;
Separator: Char;
S: Integer;
E: Integer;
L: Integer;
function GetCurrent (): string; inline;
function MoveNext (): Boolean; inline;
property Current: string read GetCurrent;
end;
TSplitStringGenerator = record
Enum: TSplitStringEnumerator;
function GetEnumerator: TSplitStringEnumerator; inline;
end;
function SplitString( const StringToParse: string; Separator: Char ): TSplitStringGenerator; //inline;
begin
Result.Enum.StringToParse := StringToParse;
Result.Enum.Separator := Separator;
Result.Enum.S := 0;
Result.Enum.E := 0;
Result.Enum.L := Length( StringToParse );
end;
procedure Test();
var
S: string;
begin
for S in SplitString( 'A;B;C', ';' ) do begin
OutputDebugString( PChar( S ) );
end;
end;
{ TSplitStringGenerator }
function TSplitStringGenerator.GetEnumerator(): TSplitStringEnumerator;
begin
Result := Enum;
end;
{ TSplitStringEnumerator }
function TSplitStringEnumerator.GetCurrent(): string;
begin
Result := Copy( StringToParse, S, E - S );
end;
function TSplitStringEnumerator.MoveNext(): Boolean;
begin
S := E + 1;
Result := S <= L;
E := S;
while ( E <= L ) and ( StringToParse[ E ] <> Separator ) do Inc( E );
end;
Solução
I have found the similar bug report #72213 on QC. The bug was fixed in Delphi 2010 (see resolution comments).
Outras dicas
That code compiles and appears to run successfully for me in Delphi 2010. The output is:
Debug Output: A Process Project4.exe (4656)
Debug Output: B Process Project4.exe (4656)
Debug Output: C Process Project4.exe (4656)
Is it possible that enumerators with records are not supported in Delphi 2007?
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow