Passing an object as an interface

It should be a simple answer, I believe that it will not be,
but taken from a larger project, I have an interface and procedure

iMyUnknown= interface(IInterface) ['..GUID..'] end; procedure WorkObject(iObj :iMyUnknown); 

I know it works

 var MyUnknown : iMyUnknown; begin if supports(obj, iMyUnknown, MyUnknown) then WorkObject(MyUnknown); 

But is it possible to do something like this?

 if supports(obj, iMyUnknown) then WorkObject(obj as iMyUnknown); 
+4
source share
3 answers

Why do you need to quit?

If obj supports the interface, and all you have to do is check that before passing it to the procedure, you can just pass the object itself. The compiler takes care of the rest. You only need the third parameter to call Supports if you want to access the interface methods.

Compile and run the code below. It should compile without errors and present you with a console window and a dialog message.

 program Project1; {$APPTYPE CONSOLE} uses Classes , Dialogs , SysUtils ; type iMyUnknown = interface(IInterface) ['{DA867EBA-8213-4A91-8E03-1AACA150CE77}'] procedure DoSomething; end; TMuster = class(TInterfacedObject, iMyUnknown) procedure DoSomething; end; procedure WorkObject(iObj: iMyUnknown); begin if Assigned(iObj) then ShowMessage('Got something'); end; { TMuster } procedure TMuster.DoSomething; begin beep; end; var obj: TMuster; begin try obj := TMuster.Create; if Supports(obj, iMyUnknown) then WorkObject(obj); except on E:Exception do Writeln(E.Classname, ': ', E.Message); end; end. 
+5
source

You can pass the object to the interface using as-cast if the compiler knows that your object supports IInterface and your interface has a GUID. Therefore, it will not work with TObject, but with TInterfacedObject it will.

+3
source

Yes, you can. The as operator has been working with interfaces since interface support was added to the language (near Delphi 3, IIRC). The code you posted works. Where is the problem?

+3
source

Source: https://habr.com/ru/post/1310922/


All Articles