私は最近、インターフェイスと D2010 RTTI を広範囲に実験しました。実行時にインターフェイスの実際の型がわかりません。文字列を使用して修飾名にアクセスできますが。
次の点を考慮してください。
program rtti_sb_1;
{$APPTYPE CONSOLE}
uses
SysUtils, Rtti, TypInfo, mynamespace in 'mynamespace.pas';
var
ctx: TRttiContext;
InterfaceType: TRttiType;
Method: TRttiMethod;
ActualParentInstance: IParent;
ChildInterfaceValue: TValue;
ParentInterfaceValue: TValue;
begin
ctx := TRttiContext.Create;
// Instantiation
ActualParentInstance := TChild.Create as IParent;
{$define WORKAROUND}
{$ifdef WORKAROUND}
InterfaceType := ctx.GetType(TypeInfo(IParent));
InterfaceType := ctx.GetType(TypeInfo(IChild));
{$endif}
// Fetch interface type
InterfaceType := ctx.FindType('mynamespace.IParent');
// This cast is OK and ChildMethod is executed
(ActualParentInstance as IChild).ChildMethod(100);
// Create a TValue holding the interface
TValue.Make(@ActualParentInstance, InterfaceType.Handle, ParentInterfaceValue);
InterfaceType := ctx.FindType('mynamespace.IChild');
// This cast doesn't work
if ParentInterfaceValue.TryCast(InterfaceType.Handle, ChildInterfaceValue) then begin
Method := InterfaceType.GetMethod('ChildMethod');
if (Method <> nil) then begin
Method.Invoke(ChildInterfaceValue, [100]);
end;
end;
ReadLn;
end.
の内容mynamespace.pas
は次のとおりです。
{$M+}
IParent = interface
['{2375F59E-D432-4D7D-8D62-768F4225FFD1}']
procedure ParentMethod(const Id: integer);
end;
{$M-}
IChild = interface(IParent)
['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
procedure ChildMethod(const Id: integer);
end;
TParent = class(TInterfacedObject, IParent)
public
procedure ParentMethod(const Id: integer);
end;
TChild = class(TParent, IChild)
public
procedure ChildMethod(const Id: integer);
end;
完全を期すために、実装は次のようになります
procedure TParent.ParentMethod(const Id: integer);
begin
WriteLn('ParentMethod executed. Id is ' + IntToStr(Id));
end;
procedure TChild.ChildMethod(const Id: integer);
begin
WriteLn('ChildMethod executed. Id is ' + IntToStr(Id));
end;
の理由は、この投稿{$define WORKAROUND}
で見つけることができます。
質問: RTTI を使用して目的の型をキャストする方法はありますか? つまり、1) 文字列としての IChild の修飾名、および 2) IParent インターフェイスとしての TChild インスタンスへの参照を知ることから IChild.ChildMethod を呼び出す方法はありますか? (結局のところ、ハードコードされたキャストは問題なく動作します。これは可能なのでしょうか?) ありがとうございます!