[Lazarus] How to cast a Interface to a Object in Lazaeus

Michael Van Canneyt michael at freepascal.org
Thu Mar 12 13:35:14 CET 2015



On Thu, 12 Mar 2015, aradeonas wrote:

> Here an example for you:
>  
> type
>  
>       { IFile }
>  
> IFile = interface
> function GetName: string;
> procedure SetName(AValue: string);
> property Name: string read GetName write SetName;
> end;
>  
> TFileList=specialize TFPGList<IFile>;
>  
>  
> { TVideoFile }
>  
> TVideoFile = class(TInterfacedPersistent, IFile)
> private
> FName: string;
> FWidth: integer;
> function GetName: string;
> procedure SetName(AValue: string);
> public
> property Name: string read GetName write SetName;
> property Width: integer read FWidth write FWidth;
> end;

You should make IVideofile with GetIWidth and so on.

> { TAudioFile }
>  
> TAudioFile = class(TInterfacedPersistent, IFile)
> private
> FName: string;
> FArtist: string;
> function GetName: string;
> procedure SetName(AValue: string);
> public
> property Name: string read GetName write SetName;
> property Artist: string read FArtist write FArtist;
> end;

Here you should make IAudioFile with GetArtist and so on.

>  
> var
> Form1: TForm1;
>  
> implementation
>  
> {$R *.lfm}
>  
> { TAudioFile }
>  
> function TAudioFile.GetName: string;
> begin
> Result:=FName;
> end;
>  
> procedure TAudioFile.SetName(AValue: string);
> begin
> FName:=AValue;
> end;
>  
> { TVideoFile }
>  
> function TVideoFile.GetName: string;
> begin
> Result:=FName;
> end;
>  
> procedure TVideoFile.SetName(AValue: string);
> begin
> FName:=AValue;
> end;
>  
>  
> { TForm1 }
>  
> procedure TForm1.FormCreate(Sender: TObject);
> var
> V1,V2:TVideoFile;
> A1,A2:TAudioFile;
> Fl:TFileList;
> begin
> Fl:=TFileList.Create;
> V1:=TVideoFile.Create;
> V1.Name:='V';
> V1.Width:=100;
> A1:=TAudioFile.Create;
> A1.Name:='A';
> A1.Artist:='Art';
> FL.Add(V1);
> FL.Add(A1);
> V2:=TVideoFile(FL.Items[0]);
> A2:=TAudioFile(Fl.Items[1]);
> ShowMessage(V2.Name);
> ShowMessage(A2.Name);
> end;
> 
>  
> What you think?

If you use interfaces all the way as suggested above, you can get one interface, 
and then query for the others as well with the IUnknown interface. then there is no need to access the objects.

Your problem is that you mix an interface with a non-interface approach.

Michael.


More information about the Lazarus mailing list