[fpc-pascal] Generic (TFPGObjectList) EInvalidCast

Mattias Gaertner nc-gaertnma at netcologne.de
Tue Dec 11 22:35:20 CET 2018


On Tue, 11 Dec 2018 22:19:11 +0100
Vojtěch Čihák <vojtech.cihak at atlas.cz> wrote:

> Hi,
>  
> why this code gives EInvalidCast at runtime (but compiles well):w
>  
> program Project1;
> {$mode objfpc}{$H+}
>  
> uses
>   {$IFDEF UNIX}{$IFDEF UseCThreads}
>   cthreads,
>   {$ENDIF}{$ENDIF}
>   Classes, fgl
>   { you can add units after this };
>  
> {$R *.res}
> type
>   TMyClass = class
>     procedure Output1;
>   end;
>  
>   TMyList = class (specialize TFPGObjectList<TMyClass>)
>  
>   end;
>  
>   TMyDescClass = class(TMyClass)
>     procedure Output2;
>   end;
>  
> var MyList: TMyList;
>     MyClass: TMyClass;
>  
> procedure TMyClass.Output1;
> begin
>   WriteLn('Output1');
> end;
>  
> procedure TMyDescClass.Output2;
> begin
>   WriteLn('Output2');
> end;
>  
> begin
>   MyList:=TMyList.Create(True);
>   MyClass:=TMyClass.Create;
>   MyList.Add(MyClass);
>   MyList[0].Output1;
>   TMyDescClass(MyList[0]);  // EInvalidCast

because MyClass is not TMyDescClass

Mattias



More information about the fpc-pascal mailing list