Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces polymorphism in Delphi

I have two interfaces one deriving from antoher:

type
  ISomeInterface = interface
    ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
  end;

  ISomeInterfaceChild = interface(ISomeInterface)
    ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
  end;

Now I have a procedure which parameter is ISomeInterface like:

procedure DoSomething(SomeInterface: ISomeInterface);

I want to check if SomeInterface is ISomeInterfaceChild. Is operator is not supported in interfaces in Delphi 7 and I can't use Supports here neither. What can I do?

like image 935
JustMe Avatar asked May 24 '26 03:05

JustMe


2 Answers

You can indeed use Supports. All you need is:

Supports(SomeInterface, ISomeInterfaceChild)

This program illustrates:

program SupportsDemo;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  ISomeInterface = interface
    ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
  end;

  ISomeInterfaceChild = interface(ISomeInterface)
    ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
  end;

procedure Test(Intf: ISomeInterface);
begin
  Writeln(BoolToStr(Supports(Intf, ISomeInterfaceChild), True));
end;

type
  TSomeInterfaceImpl = class(TInterfacedObject, ISomeInterface);
  TSomeInterfaceChildImpl = class(TInterfacedObject, ISomeInterface, ISomeInterfaceChild);

begin
  Test(TSomeInterfaceImpl.Create);
  Test(TSomeInterfaceChildImpl.Create);
  Readln;
end.

Output

False
True
like image 111
David Heffernan Avatar answered May 26 '26 19:05

David Heffernan


Why do you say you can't use the Supports function? It seems to be the solution, it has an overloaded version which takes IInterface as the first parameter so

procedure DoSomething(SomeInterface: ISomeInterface);
var tmp: ISomeInterfaceChild;
begin
  if(Supports(SomeInterface, ISomeInterfaceChild, tmp))then begin
     // argument is ISomeInterfaceChild
  end;

should do what you want.

like image 31
ain Avatar answered May 26 '26 20:05

ain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!