This week I had to maintain some legacy code that uses many interfaces and supports in order to find out if a specific interface is supported:
type
IMyInterface = interface(IInterface)
['{F500EEDD-032E-4D15-A8C0-EFF673C2AF01}']
procedure DoSomething;
end;
procedure MyProcedure(const AIntf: IInterface);
implementation
uses
System.SysUtils;
procedure MyProcedure(const AIntf: IInterface);
var
lMyIntf: IMyInterface;
begin
if Supports(AIntf, IInterface, lMyIntf) then
lMyIntf.DoSomething;
end;
One of the tasks I had to do is to replace the interfaces with pure Delphi objects. That’s why I wondered if there is a chance to write something similar for objects.
I played a bit and found the following:
type
TObjectHelper = class helper for TObject
public
function Supports<T: class>(out ADest: T): Boolean;
end;
...
{ TObjectHelper }
function TObjectHelper.Supports<T>(out ADest: T): Boolean;
begin
if Self.InheritsFrom(T) then
begin
ADest := T(Self);
Result := True;
end
else
begin
ADest := nil;
Result := False;
end;
end;
...
var
lObject: TObject;
lMyObject: TMyObject;
begin
...
if lObject.Supports<TMyObject>(lMyObject) then
lMyObject.DoSomething;



