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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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; |