From Asbjørn, 1 Year ago, written in Delphi (Object Pascal).
Embed
  1. uses
  2.   System.SysUtils, System.TypInfo, System.Rtti;
  3.  
  4. type
  5.   IWidget<T> = interface
  6.     procedure SetInstance(const Inst: T);
  7.   end;
  8.  
  9.   TWidgetImpl<T> = class(TInterfacedObject, IWidget<T>)
  10.   public
  11.     procedure SetInstance(const Inst: T);
  12.   end;
  13.  
  14. { TWidgetImpl<T> }
  15.  
  16. procedure TWidgetImpl<T>.SetInstance(const Inst: T);
  17. var
  18.   ctx: TRttiContext;
  19.   typ: TRttiType;
  20.   m: TRttiMethod;
  21. begin
  22.   typ := ctx.GetType(TypeInfo(T));
  23.   m := typ.GetMethod('Initialize');
  24.   if (Assigned(m)) then
  25.   begin
  26.     m.Invoke(TValue.From<T>(Inst), []);
  27.   end;
  28. end;
  29.  
  30. type
  31.   TObjInst = class
  32.   public
  33.     procedure Initialize;
  34.   end;
  35.  
  36. { TObjInst }
  37.  
  38. procedure TObjInst.Initialize;
  39. begin
  40.   WriteLn('TObjInst.Initialize');
  41. end;
  42.  
  43. type
  44.   IIntfInst = interface(IInvokable)
  45.     procedure Initialize;
  46.   end;
  47.  
  48.   TIntfInstImpl = class(TInterfacedObject, IIntfInst)
  49.   public
  50.     procedure Initialize;
  51.   end;
  52.  
  53. { TIntfInstImpl }
  54.  
  55. procedure TIntfInstImpl.Initialize;
  56. begin
  57.   WriteLn('IIntfInst.Initialize');
  58. end;
  59.  
  60. var
  61.   wo: IWidget<TObjInst>;
  62.   o: TObjInst;
  63.   wi: IWidget<IIntfInst>;
  64.   i: IIntfInst;
  65. begin
  66.   wo := TWidgetImpl<TObjInst>.Create;
  67.   o := TObjInst.Create;
  68.   wo.SetInstance(o);
  69.  
  70.  
  71.   wi := TWidgetImpl<IIntfInst>.Create;
  72.   i := TIntfInstImpl.Create;
  73.   wi.SetInstance(i);
  74.  
  75.   ReadLn;
  76. end.
  77.  

Replies to Invokable rss

Title Name Language When
Re: Invokable Mature Leopard delphi 1 Year ago.
Re: Invokable Social Madrill delphi 1 Year ago.

captcha