System.SysUtils, System.TypInfo, System.Rtti;
type
IWidget<T> = interface
procedure SetInstance(const Inst: T);
end;
TWidgetImpl<T> = class(TInterfacedObject, IWidget<T>)
public
procedure SetInstance(const Inst: T);
end;
{ TWidgetImpl<T> }
-------------------------
procedure TWidgetImpl<T>.SetInstance(const Inst: T);
var
ctx: TRttiContext;
typ: TRttiType;
m: TRttiMethod;
begin
typ := ctx.GetType(TypeInfo(T));
m := typ.GetMethod('Initialize');
if (Assigned(m)) then
begin
m.Invoke(TValue.From<T>(Inst), []);
end;
type
TObjInst = class
public
procedure Initialize;
end;
{ TObjInst }
procedure TObjInst.Initialize;
begin
WriteLn('TObjInst.Initialize');
end;
type
IIntfInst = interface(IInvokable)
procedure Initialize;
end;
TIntfInstImpl = class(TInterfacedObject, IIntfInst)
public
procedure Initialize;
end;
{ TIntfInstImpl }
procedure TIntfInstImpl.Initialize;
begin
WriteLn('IIntfInst.Initialize');
end;
var
wo: IWidget<TObjInst>;
o: TObjInst;
wi: IWidget<IIntfInst>;
i: IIntfInst;
begin
wo
--------------
I have a private var (fSubscriber) of T and I get access like this:
typ :=
o := TObjInst.Create;
wo.SetInstance(o);
wi := TWidgetImpl<IIntfInst>.Create;
i := TIntfInstImpl.Create;
wi.SetInstance(i);
ReadLn;
end.
....
m.Invoke((fSubscriber as TObject),[]);
Your code is different in these two lines. I think I tried to use TypeInfo and didn't work nicely if I recall correctly.
Is it wrong what I am doing?
Thanks